use crate::error::{ParseError, Result};
use crate::proto::*;  // 直接导入 proto 模块中的所有类型
use lazy_static::lazy_static;
use prost::Message;
use regex::Regex;
use std::collections::{HashMap, HashSet};
use std::fs;

/// Signal information for feedthrough modification
#[derive(Clone)]
struct SignalInfo {
    from_port: String,
    to_port: String,
    wire_name: String,
    from_direction: String,
    to_direction: String,
    port_width: String,
    from_port_line: u32,  // Line number of the port in source instance
    to_port_line: u32,    // Line number of the port in target instance
}

/// Verilog 解析器
pub struct VerilogParser {
    database: ModbDatabase,
    module_map: HashMap<String, usize>,
}

impl VerilogParser {
    /// 创建新的解析器
    pub fn new() -> Self {
        Self {
            database: ModbDatabase {
                modules: Vec::new(),
                macros: Vec::new(),
            },
            module_map: HashMap::new(),
        }
    }
    
    /// Parse Verilog file
    pub fn parse_verilog_file(&mut self, file_path: &str, module_name: Option<&str>) -> Result<()> {
        println!("Parsing: {}", file_path);
        
        // Resolve environment variables
        let resolved_path = match self.resolve_env_vars(file_path) {
            Ok(path) => path,
            Err(e) => {
                eprintln!("Warning: Failed to resolve path: {} - {}", file_path, e);
                return Ok(()); // Skip this file, continue execution
            }
        };
        
        // Read file
        let content = match fs::read_to_string(&resolved_path) {
            Ok(c) => c,
            Err(e) => {
                eprintln!("Warning: File not found or unreadable: {} - {}", resolved_path, e);
                return Ok(()); // Skip this file, continue execution
            }
        };
        
        // Remove comments
        let content = self.remove_comments(&content);
        
        // Parse macros
        self.parse_macros(&content)?;
        
        // Parse modules
        if let Some(name) = module_name {
            self.parse_module(&content, name)?;
            println!("Parsed module: {}", name);
        } else {
            self.parse_all_modules(&content)?;
        }
        
        Ok(())
    }
    
    /// 解析 Verilog 文件列表
    pub fn parse_verilog_file_list(&mut self, list_file: &str, module_name: Option<&str>) -> Result<()> {
        let mut processed_files = HashSet::new();
        self.parse_verilog_file_list_recursive(list_file, module_name, &mut processed_files)
    }
    
    /// 递归解析文件列表（支持嵌套）
    fn parse_verilog_file_list_recursive(
        &mut self,
        list_file: &str,
        module_name: Option<&str>,
        processed_files: &mut HashSet<String>,
    ) -> Result<()> {
        // 解析环境变量
        let resolved_path = self.resolve_env_vars(list_file)?;
        
        // 检查循环引用
        if processed_files.contains(&resolved_path) {
            return Err(ParseError::CircularReference(resolved_path));
        }
        processed_files.insert(resolved_path.clone());
        
        // 读取文件列表
        let content = fs::read_to_string(&resolved_path)
            .map_err(|_| ParseError::FileNotFound(resolved_path.clone()))?;
        
        for line in content.lines() {
            let line = line.trim();
            
            // 跳过空行和注释
            if line.is_empty() || self.is_comment_or_directive(line) {
                continue;
            }
            
            // Handle -f nested file lists
            if line.starts_with("-f ") {
                let nested_file = line[3..].trim();
                if let Err(e) = self.parse_verilog_file_list_recursive(nested_file, module_name, processed_files) {
                    eprintln!("Warning: Failed to parse file list: {} - {}", nested_file, e);
                    // Continue processing other files
                }
                continue;
            }
            
            // Parse Verilog file
            if line.ends_with(".v") || line.ends_with(".sv") {
                if let Err(e) = self.parse_verilog_file(line, module_name) {
                    eprintln!("Warning: Failed to parse file: {} - {}", line, e);
                    // Continue processing other files
                }
            }
        }
        
        Ok(())
    }
    
    /// 解析环境变量
    fn resolve_env_vars(&self, path: &str) -> Result<String> {
        lazy_static! {
            static ref ENV_VAR_REGEX: Regex = Regex::new(r"\$\{?(\w+)\}?").unwrap();
        }
        
        let mut result = path.to_string();
        
        for caps in ENV_VAR_REGEX.captures_iter(path) {
            let full_match = caps.get(0).unwrap().as_str();
            let var_name = caps.get(1).unwrap().as_str();
            
            if let Ok(value) = std::env::var(var_name) {
                result = result.replace(full_match, &value);
            } else {
                return Err(ParseError::EnvVarError(format!(
                    "Environment variable undefined: {}",
                    var_name
                )));
            }
        }
        
        Ok(result)
    }
    
    /// 移除注释
    /// Remove comments using token-based lexical analysis instead of regex
    /// This avoids the bug where /* */ regex incorrectly matches across module boundaries
    fn remove_comments(&self, content: &str) -> String {
        let mut result = String::new();
        let chars: Vec<char> = content.chars().collect();
        let len = chars.len();
        let mut i = 0;
        
        while i < len {
            // Check for single-line comment
            if i + 1 < len && chars[i] == '/' && chars[i + 1] == '/' {
                // Skip until end of line
                while i < len && chars[i] != '\n' {
                    i += 1;
                }
                // Keep the newline
                if i < len {
                    result.push(chars[i]);
                    i += 1;
                }
                continue;
            }
            
            // Check for multi-line comment
            if i + 1 < len && chars[i] == '/' && chars[i + 1] == '*' {
                i += 2; // Skip /*
                // Skip until we find */
                while i + 1 < len {
                    if chars[i] == '*' && chars[i + 1] == '/' {
                        i += 2; // Skip */
                        break;
                    }
                    // Preserve newlines in comments to maintain line numbers
                    if chars[i] == '\n' {
                        result.push('\n');
                    }
                    i += 1;
                }
                continue;
            }
            
            // Check for string literals (don't process comments inside strings)
            if chars[i] == '"' {
                result.push(chars[i]);
                i += 1;
                // Copy everything until closing quote
                while i < len {
                    result.push(chars[i]);
                    if chars[i] == '"' && (i == 0 || chars[i - 1] != '\\') {
                        i += 1;
                        break;
                    }
                    i += 1;
                }
                continue;
            }
            
            // Regular character
            result.push(chars[i]);
            i += 1;
        }
        
        result
    }
    
    /// 判断是否为注释或编译器指令
    fn is_comment_or_directive(&self, line: &str) -> bool {
        line.starts_with("//") 
            || line.starts_with("#") 
            || line.starts_with("/*")
            || line.starts_with("+define")
            || line.starts_with("+incdir")
    }
    
    /// 解析宏定义
    fn parse_macros(&mut self, content: &str) -> Result<()> {
        lazy_static! {
            static ref MACRO_REGEX: Regex = Regex::new(r"`define\s+(\w+)\s*(.*)").unwrap();
        }
        
        for caps in MACRO_REGEX.captures_iter(content) {
            let name = caps.get(1).unwrap().as_str().to_string();
            let value = caps.get(2).map(|m| m.as_str()).unwrap_or("").to_string();
            
            let macro_type = if value.is_empty() {
                0 // 纯定义宏开关
            } else if value.contains('(') {
                2 // 有值表达式宏
            } else {
                1 // 有值纯净宏
            };
            
            self.database.macros.push(MacroDefine {
                name,
                value,
                r#type: macro_type,
            });
        }
        
        Ok(())
    }
    
    /// Parse all modules using token-based lexical analysis
    fn parse_all_modules(&mut self, content: &str) -> Result<()> {
        let chars: Vec<char> = content.chars().collect();
        let len = chars.len();
        let mut i = 0;
        let mut module_count = 0;
        let mut failed_count = 0;
        
        // Build a map of module_name -> (start_pos, end_pos) in ONE pass
        let mut module_positions: Vec<(String, usize, usize)> = Vec::new();
        
        while i < len {
            // Skip whitespace
            while i < len && chars[i].is_whitespace() {
                i += 1;
            }
            
            if i >= len {
                break;
            }
            
            // Check if this is the keyword "module"
            if self.match_keyword(&chars, i, "module") {
                let module_start = i;
                i += 6; // Skip "module"
                
                // Skip whitespace after "module"
                while i < len && chars[i].is_whitespace() {
                    i += 1;
                }
                
                // Extract the module name (must start with letter or underscore)
                if i < len && (chars[i].is_alphabetic() || chars[i] == '_') {
                    let name_start = i;
                    while i < len && (chars[i].is_alphanumeric() || chars[i] == '_') {
                        i += 1;
                    }
                    let module_name: String = chars[name_start..i].iter().collect();
                    
                    // Find matching endmodule
                    let mut depth = 1;
                    while i < len && depth > 0 {
                        // Skip whitespace
                        while i < len && chars[i].is_whitespace() {
                            i += 1;
                        }
                        
                        if i >= len {
                            break;
                        }
                        
                        // Check for nested "module"
                        if self.match_keyword(&chars, i, "module") {
                            depth += 1;
                            i += 6;
                            continue;
                        }
                        
                        // Check for "endmodule"
                        if self.match_keyword(&chars, i, "endmodule") {
                            depth -= 1;
                            if depth == 0 {
                                i += 9; // Skip "endmodule"
                                module_positions.push((module_name.clone(), module_start, i));
                                module_count += 1;
                                break;
                            }
                            i += 9;
                            continue;
                        }
                        
                        i += 1;
                    }
                    // After finding a complete module, continue to next iteration
                    // Don't fall through to the else branch
                    continue;
                }
            }
            
            // Only increment if we didn't match a module keyword
            i += 1;
        }
        
        // Second pass: parse each module using cached positions
        for (module_name, start_pos, end_pos) in module_positions {
            let module_content: String = chars[start_pos..end_pos].iter().collect();
            
            if let Err(e) = self.parse_module_from_content(&module_content, &module_name) {
                eprintln!("Warning: Failed to parse module {} - {}", module_name, e);
                failed_count += 1;
            }
        }
        
        // Only print summary if multiple modules found or if there are failures
        if module_count > 1 || failed_count > 0 {
            if failed_count > 0 {
                println!("Parsing complete: {} modules found, {} failed", module_count, failed_count);
            } else {
                println!("Parsing complete: {} modules found", module_count);
            }
        }
        
        Ok(())
    }
    
    /// 解析单个模块
    fn parse_module(&mut self, content: &str, name: &str) -> Result<()> {
        // 提取模块内容
        let module_content = self.extract_module_content(content, name)?;
        self.parse_module_from_content(&module_content, name)
    }
    
    /// Parse module from pre-extracted content (performance optimization)
    fn parse_module_from_content(&mut self, module_content: &str, name: &str) -> Result<()> {
        let mut module = Module {
            name: name.to_string(),
            parameters: Vec::new(),
            ports: Vec::new(),
            wires: Vec::new(),
            instances: Vec::new(),
            info: module_content.to_string(),
            max_port_name_len: 0,
            max_port_width_len: 0,
            max_param_name_len: 0,
            max_param_value_len: 0,
            max_wire_name_len: 0,
        };
        
        // 预处理条件编译指令（仅用于实例解析）
        let preprocessed_content = self.preprocess_conditionals(module_content);
        
        // 解析各个部分
        // 参数和端口使用原始内容，以保留 ifdef 信息到 attribute 字段
        self.parse_parameters(module_content, &mut module)?;
        self.parse_ports(module_content, &mut module)?;
        self.parse_wires(&preprocessed_content, &mut module)?;
        self.parse_instances(module_content, &mut module)?;
        
        // 计算统计信息
        self.calculate_module_statistics(&mut module);
        
        // 添加到数据库
        let index = self.database.modules.len();
        self.module_map.insert(name.to_string(), index);
        self.database.modules.push(module);
        
        Ok(())
    }
    
    /// 计算模块的统计信息用于格式化对齐
    fn calculate_module_statistics(&self, module: &mut Module) {
        // 计算最大端口名长度
        module.max_port_name_len = module.ports.iter()
            .map(|p| p.name.len() as u32)
            .max()
            .unwrap_or(0);
        
        // 计算最大端口位宽表达式长度
        module.max_port_width_len = module.ports.iter()
            .map(|p| p.width.len() as u32)
            .max()
            .unwrap_or(0);
        
        // 计算最大参数名长度
        module.max_param_name_len = module.parameters.iter()
            .map(|p| p.name.len() as u32)
            .max()
            .unwrap_or(0);
        
        // 计算最大参数值长度
        module.max_param_value_len = module.parameters.iter()
            .map(|p| p.value.len() as u32)
            .max()
            .unwrap_or(0);
        
        // 计算最大wire名长度
        module.max_wire_name_len = module.wires.iter()
            .map(|w| w.name.len() as u32)
            .max()
            .unwrap_or(0);
    }
    
    /// Extract module content using token-based parsing instead of regex
    /// This correctly handles nested structures and avoids regex limitations
    fn extract_module_content(&self, content: &str, name: &str) -> Result<String> {
        let chars: Vec<char> = content.chars().collect();
        let len = chars.len();
        let mut i = 0;
        
        // Find "module <name>"
        while i < len {
            // Skip whitespace
            while i < len && chars[i].is_whitespace() {
                i += 1;
            }
            
            if i >= len {
                break;
            }
            
            // Check if this is the keyword "module"
            if self.match_keyword(&chars, i, "module") {
                let module_start = i;
                i += 6; // Skip "module"
                
                // Skip whitespace after "module"
                while i < len && chars[i].is_whitespace() {
                    i += 1;
                }
                
                // Extract the module name
                let name_start = i;
                while i < len && (chars[i].is_alphanumeric() || chars[i] == '_') {
                    i += 1;
                }
                let found_name: String = chars[name_start..i].iter().collect();
                
                // Check if this is the module we're looking for
                if found_name == name {
                    // Find the matching "endmodule"
                    let mut depth = 1;
                    let content_start = module_start;
                    
                    while i < len && depth > 0 {
                        // Skip whitespace
                        while i < len && chars[i].is_whitespace() {
                            i += 1;
                        }
                        
                        if i >= len {
                            break;
                        }
                        
                        // Check for nested "module"
                        if self.match_keyword(&chars, i, "module") {
                            depth += 1;
                            i += 6;
                            continue;
                        }
                        
                        // Check for "endmodule"
                        if self.match_keyword(&chars, i, "endmodule") {
                            depth -= 1;
                            if depth == 0 {
                                i += 9; // Skip "endmodule"
                                let module_content: String = chars[content_start..i].iter().collect();
                                return Ok(module_content);
                            }
                            i += 9;
                            continue;
                        }
                        
                        i += 1;
                    }
                    
                    // If we get here, we didn't find matching endmodule
                    return Err(ParseError::ModuleNotFound(format!("endmodule not found for {}", name)));
                }
            } else {
                i += 1;
            }
        }
        
        Err(ParseError::ModuleNotFound(name.to_string()))
    }
    
    /// Helper function to match a keyword at a specific position
    /// Returns true only if the keyword is followed by a non-identifier character
    fn match_keyword(&self, chars: &[char], pos: usize, keyword: &str) -> bool {
        let keyword_chars: Vec<char> = keyword.chars().collect();
        let keyword_len = keyword_chars.len();
        
        // Check if there's enough space
        if pos + keyword_len > chars.len() {
            return false;
        }
        
        // Check if characters match
        for (i, &kc) in keyword_chars.iter().enumerate() {
            if chars[pos + i] != kc {
                return false;
            }
        }
        
        // Check that it's not part of a larger identifier
        // There should be a non-identifier character before (if not at start)
        if pos > 0 {
            let prev_char = chars[pos - 1];
            if prev_char.is_alphanumeric() || prev_char == '_' {
                return false;
            }
        }
        
        // There should be a non-identifier character after (if not at end)
        if pos + keyword_len < chars.len() {
            let next_char = chars[pos + keyword_len];
            if next_char.is_alphanumeric() || next_char == '_' {
                return false;
            }
        }
        
        true
    }
    
    /// 解析参数
    fn parse_parameters(&self, content: &str, module: &mut Module) -> Result<()> {
        lazy_static! {
            static ref PARAM_REGEX: Regex = 
                Regex::new(r"parameter\s+(?:\[.*?\])?\s*(\w+)\s*=\s*([^,;]+)").unwrap();
        }
        
        let mut param_id = 1;
        for caps in PARAM_REGEX.captures_iter(content) {
            let name = caps.get(1).unwrap().as_str().to_string();
            let value = caps.get(2).unwrap().as_str().trim().to_string();
            
            module.parameters.push(Parameter {
                name,
                value,
                attribute: String::new(),
                id: param_id,
            });
            param_id += 1;
        }
        
        Ok(())
    }
    
    /// 解析端口
    fn parse_ports(&self, content: &str, module: &mut Module) -> Result<()> {
        lazy_static! {
            static ref PORT_REGEX: Regex = 
                Regex::new(r"(input|output|inout)\s+(?:wire\s+|reg\s+)?(\[(?:\s*[^\]]+\s*\]\s*\[\s*[^\]]+\s*|\s*[^\]]+\s*)\]\s+)?(\w+)").unwrap();
            static ref IFDEF_REGEX: Regex = Regex::new(r"`ifdef\s+(\w+)").unwrap();
            static ref IFNDEF_REGEX: Regex = Regex::new(r"`ifndef\s+(\w+)").unwrap();
            static ref ENDIF_REGEX: Regex = Regex::new(r"`endif").unwrap();
        }
        
        let mut port_id = 1;
        let lines: Vec<&str> = content.lines().collect();
        let mut ifdef_stack: Vec<String> = Vec::new();
        
        for line in lines {
            let trimmed = line.trim();
            
            // Track ifdef/ifndef/endif
            if let Some(caps) = IFDEF_REGEX.captures(trimmed) {
                let macro_name = caps.get(1).unwrap().as_str();
                ifdef_stack.push(format!("`ifdef {}", macro_name));
                continue;
            }
            
            if let Some(caps) = IFNDEF_REGEX.captures(trimmed) {
                let macro_name = caps.get(1).unwrap().as_str();
                ifdef_stack.push(format!("`ifndef {}", macro_name));
                continue;
            }
            
            if ENDIF_REGEX.is_match(trimmed) {
                ifdef_stack.pop();
                continue;
            }
            
            // Parse port declaration
            if let Some(caps) = PORT_REGEX.captures(line) {
                let direction = caps.get(1).unwrap().as_str().to_string();
                let width_with_space = caps.get(2).map(|m| m.as_str()).unwrap_or("");
                let width = width_with_space.trim_end().to_string();
                let name = caps.get(3).unwrap().as_str().to_string();
                
                // Record attribute (ifdef context)
                let attribute = if !ifdef_stack.is_empty() {
                    ifdef_stack.last().unwrap().clone()
                } else {
                    String::new()
                };
                
                module.ports.push(Port {
                    name,
                    direction,
                    width,
                    r#type: "wire".to_string(),
                    attribute,
                    id: port_id,
                });
                port_id += 1;
            }
        }
        
        Ok(())
    }
    
    /// 解析线网
    fn parse_wires(&self, content: &str, module: &mut Module) -> Result<()> {
        lazy_static! {
            static ref WIRE_REGEX: Regex = 
                Regex::new(r"wire\s+(\[(?:\s*[^\]]+\s*\]\s*\[\s*[^\]]+\s*|\s*[^\]]+\s*)\])?\s*(\w+)").unwrap();
        }
        
        let mut wire_id = 1;
        for caps in WIRE_REGEX.captures_iter(content) {
            let width = caps.get(1).map(|m| m.as_str()).unwrap_or("").to_string();
            let name = caps.get(2).unwrap().as_str().to_string();
            
            module.wires.push(Wire {
                name,
                width,
                attribute: String::new(),
                connections: Vec::new(),
                id: wire_id,
            });
            wire_id += 1;
        }
        
        Ok(())
    }
    
    /// 预处理条件编译指令
    fn preprocess_conditionals(&self, content: &str) -> String {
        lazy_static! {
            // 匹配 `ifdef...`else...`endif 或 `ifdef...`endif 块
            static ref IFDEF_ELSE_ENDIF: Regex = Regex::new(
                r"(?s)`ifdef\s+\w+\s*([^`]*?)`else\s*([^`]*?)`endif"
            ).unwrap();
            static ref IFDEF_ENDIF: Regex = Regex::new(
                r"(?s)`ifdef\s+\w+\s*([^`]*?)`endif"
            ).unwrap();
            static ref IFNDEF_ELSE_ENDIF: Regex = Regex::new(
                r"(?s)`ifndef\s+\w+\s*([^`]*?)`else\s*([^`]*?)`endif"
            ).unwrap();
            static ref IFNDEF_ENDIF: Regex = Regex::new(
                r"(?s)`ifndef\s+\w+\s*([^`]*?)`endif"
            ).unwrap();
        }
        
        let mut result = content.to_string();
        
        // 处理 `ifdef...`else...`endif: 保留else分支（默认选择最后一个选项）
        result = IFDEF_ELSE_ENDIF.replace_all(&result, "$2").to_string();
        
        // 处理 `ifdef...`endif: 移除ifdef块内容（宏未定义时的默认行为）
        result = IFDEF_ENDIF.replace_all(&result, "").to_string();
        
        // 处理 `ifndef...`else...`endif: 保留ifdef分支（ifndef取反逻辑）
        result = IFNDEF_ELSE_ENDIF.replace_all(&result, "$1").to_string();
        
        // 处理 `ifndef...`endif: 保留ifndef块内容（ifndef取反逻辑）
        result = IFNDEF_ENDIF.replace_all(&result, "$1").to_string();
        
        result
    }

    /// 解析实例（基于段分割的结构化方法）
    fn parse_instances(&self, content: &str, module: &mut Module) -> Result<()> {
        // 第零步：预处理条件编译指令（处理 `ifdef 等）
        let preprocessed_content = self.preprocess_conditionals(content);
        
        // 第一步：提取实例化段（instance declaration section）
        let instance_section = self.extract_instance_section(&preprocessed_content);
        
        // 第二步：在实例化段中识别每个实例
        // 传递原始预处理后的内容，以便计算正确的绝对行号
        let instances = self.parse_instance_statements(&instance_section, &preprocessed_content);
        
        // 第三步：添加到模块
        let mut inst_id = 1;
        for inst in instances {
            module.instances.push(Instance {
                module_name: inst.0,
                name: inst.1,
                attribute: inst.2,
                id: inst_id,
                line_number_start: inst.3,
                line_number_end: inst.4,
                port_connections: inst.5,  // 端口连接
            });
            inst_id += 1;
        }
        
        // 第四步：根据实例的端口连接构建 wire 的 connections
        self.build_wire_connections(module)?;
        
        Ok(())
    }
    
    /// 根据实例的端口连接构建 wire 的 connections
    /// 注意：Verilog 允许隐式 wire 声明，即单比特信号可以不显式声明
    fn build_wire_connections(&self, module: &mut Module) -> Result<()> {
        use crate::proto::Connection;
        
        // 为每个信号（包括隐式 wire）构建 connections 列表
        let mut wire_connections: HashMap<String, Vec<Connection>> = HashMap::new();
        
        // 遍历所有实例的端口连接，收集所有使用的信号
        for inst in &module.instances {
            for port_conn in &inst.port_connections {
                // 提取信号名（支持拼接，可能返回多个信号）
                let signal_names = self.extract_signal_names(&port_conn.signal_expr);
                
                // 为每个信号添加连接
                for signal_name in signal_names {
                    if !signal_name.is_empty() {
                        // 构造连接名: instance.port
                        let conn_name = format!("{}.{}", inst.name, port_conn.port_name);
                        
                        // 添加到信号的 connections
                        wire_connections.entry(signal_name)
                            .or_insert_with(Vec::new)
                            .push(Connection {
                                name: conn_name.clone(),
                                r#type: String::new(),  // 类型后续可以扩充
                            });
                    }
                }
            }
        }
        
        // 1. 更新已声明的 wire 的 connections
        for wire in &mut module.wires {
            if let Some(conns) = wire_connections.get(&wire.name) {
                wire.connections = conns.clone();
            }
        }
        
        // 2. 为隐式 wire（在 port_connections 中使用但未在 wires 中声明的信号）创建 Wire 对象
        let mut wire_id = (module.wires.len() + 1) as u32;
        let existing_wire_names: HashSet<String> = module.wires.iter()
            .map(|w| w.name.clone())
            .collect();
        
        let port_names: HashSet<String> = module.ports.iter()
            .map(|p| p.name.clone())
            .collect();
        
        for (signal_name, conns) in wire_connections {
            // 如果信号不在已声明的 wire 列表中，且不是端口，则添加为隐式 wire
            if !existing_wire_names.contains(&signal_name) && !port_names.contains(&signal_name) {
                module.wires.push(Wire {
                    name: signal_name,
                    width: String::new(),  // 隐式 wire 默认是单比特
                    attribute: String::from("implicit"),  // 标记为隐式声明
                    connections: conns,
                    id: wire_id,
                });
                wire_id += 1;
            }
        }
        
        Ok(())
    }
    
    /// 从信号表达式中提取所有信号名
    /// 例如："signal[7:0]" -> vec!["signal"]
    ///      "{a, b, c}" -> vec!["a", "b", "c"] (支持拼接)
    ///      "1'b0" -> vec![] (常量不处理)
    ///      "{TX_P,TX_N}" -> vec!["TX_P", "TX_N"]
    ///      "{4{clk}}" -> vec!["clk", "clk", "clk", "clk"] (支持复制语法)
    ///      "{2{a[3:0]}}" -> vec!["a", "a"] (支持复制)
    pub fn extract_signal_names(&self, signal_expr: &str) -> Vec<String> {
        let trimmed = signal_expr.trim();
        let mut signals = Vec::new();
        
        // 跳过空信号
        if trimmed.is_empty() {
            return signals;
        }
        
        // 跳过常量（如 1'b0, 8'hFF）
        if trimmed.contains('\'') {
            return signals;
        }
        
        // 处理拼接（如 {a, b, c} 或 {TX_P,TX_N} 或 {4{clk}}）
        if trimmed.starts_with('{') && trimmed.ends_with('}') {
            // 提取大括号内的内容
            let inner = &trimmed[1..trimmed.len()-1];
            
            // 检查是否是复制语法：{n{signal}}
            if let Some((repeat_count, repeated_expr)) = self.parse_replication(inner) {
                // 复制语法：递归提取被复制的信号
                let base_signals = self.extract_signal_names(&repeated_expr);
                
                // 复制 n 次
                for _ in 0..repeat_count {
                    for sig in &base_signals {
                        signals.push(sig.clone());
                    }
                }
                
                return signals;
            }
            
            // 普通拼接：按逗号分割，支持嵌套的大括号和括号
            let parts = self.split_concatenation(inner);
            
            for part in parts {
                let part = part.trim();
                
                // 递归处理每个部分（可能包含嵌套的拼接或复制）
                if part.starts_with('{') && part.ends_with('}') {
                    let nested_signals = self.extract_signal_names(part);
                    signals.extend(nested_signals);
                } else {
                    // 跳过常量
                    if part.contains('\'') {
                        continue;
                    }
                    
                    // 提取信号名（去除位选择）
                    let signal_name = if let Some(idx) = part.find('[') {
                        part[..idx].trim().to_string()
                    } else {
                        part.to_string()
                    };
                    
                    if !signal_name.is_empty() {
                        signals.push(signal_name);
                    }
                }
            }
            
            return signals;
        }
        
        // 单个信号：提取信号名（去除位选择）
        let signal_name = if let Some(idx) = trimmed.find('[') {
            trimmed[..idx].trim().to_string()
        } else {
            trimmed.to_string()
        };
        
        if !signal_name.is_empty() {
            signals.push(signal_name);
        }
        
        signals
    }
    
    /// 解析复制语法：{n{expr}} -> (n, "expr")
    /// 例如："4{clk}" -> Some((4, "clk"))
    ///      "2{bus[3:0]}" -> Some((2, "bus[3:0]"))
    ///      "a, b" -> None (不是复制语法)
    fn parse_replication(&self, expr: &str) -> Option<(usize, String)> {
        let trimmed = expr.trim();
        
        // 查找第一个大括号的位置
        let first_brace = trimmed.find('{')?;
        
        // 提取复制次数部分
        let count_str = trimmed[..first_brace].trim();
        
        // 如果没有数字，不是复制语法
        if count_str.is_empty() {
            return None;
        }
        
        // 尝试解析为数字
        let repeat_count = count_str.parse::<usize>().ok()?;
        
        // 检查是否有匹配的右大括号
        if !trimmed.ends_with('}') {
            return None;
        }
        
        // 提取大括号内的内容
        let inner_start = first_brace + 1;
        let inner_end = trimmed.len() - 1;
        
        if inner_start >= inner_end {
            return None;
        }
        
        let inner_expr = trimmed[inner_start..inner_end].to_string();
        
        Some((repeat_count, inner_expr))
    }
    
    /// 分割拼接表达式中的各个部分（支持嵌套）
    /// 例如："a, b[3:0], {c, d}" -> vec!["a", "b[3:0]", "{c, d}"]
    fn split_concatenation(&self, expr: &str) -> Vec<String> {
        let mut parts = Vec::new();
        let mut current = String::new();
        let mut brace_depth = 0;
        let mut bracket_depth = 0;
        let mut paren_depth = 0;
        
        for ch in expr.chars() {
            match ch {
                '{' => {
                    brace_depth += 1;
                    current.push(ch);
                }
                '}' => {
                    brace_depth -= 1;
                    current.push(ch);
                }
                '[' => {
                    bracket_depth += 1;
                    current.push(ch);
                }
                ']' => {
                    bracket_depth -= 1;
                    current.push(ch);
                }
                '(' => {
                    paren_depth += 1;
                    current.push(ch);
                }
                ')' => {
                    paren_depth -= 1;
                    current.push(ch);
                }
                ',' => {
                    if brace_depth == 0 && bracket_depth == 0 && paren_depth == 0 {
                        // 顶层逗号，分割
                        if !current.trim().is_empty() {
                            parts.push(current.trim().to_string());
                        }
                        current.clear();
                    } else {
                        current.push(ch);
                    }
                }
                _ => {
                    current.push(ch);
                }
            }
        }
        
        // 添加最后一部分
        if !current.trim().is_empty() {
            parts.push(current.trim().to_string());
        }
        
        parts
    }
    
    /// Calculate the actual bit width of a wire expression considering bit selection
    /// Examples:
    ///   "wire_name" + "[15:0]" -> "[15:0]" (use target port width)
    ///   "wire_name[7]" + "[0:0]" -> "" (single bit selection)
    ///   "wire_name[10:5]" + "[7:0]" -> "[5:0]" (6-bit range selection)
    fn calculate_wire_actual_width(&self, wire_name: &str, target_port_width: &str) -> String {
        // Check if wire_name contains bit selection
        if let Some(bracket_start) = wire_name.find('[') {
            if let Some(bracket_end) = wire_name.find(']') {
                let bit_select = &wire_name[bracket_start+1..bracket_end];
                
                // Check if it's a range selection [high:low]
                if let Some(colon_pos) = bit_select.find(':') {
                    let high_str = bit_select[..colon_pos].trim();
                    let low_str = bit_select[colon_pos+1..].trim();
                    
                    if let (Ok(high), Ok(low)) = (high_str.parse::<u32>(), low_str.parse::<u32>()) {
                        let width = if high >= low { high - low + 1 } else { low - high + 1 };
                        if width > 1 {
                            return format!("[{}:0]", width - 1);
                        } else {
                            return String::new(); // Single bit
                        }
                    }
                } else {
                    // Single bit selection [n]
                    return String::new();
                }
            }
        }
        
        // No bit selection in wire_name, use target port width
        target_port_width.to_string()
    }
    
    /// Sanitize wire name to be a valid Verilog identifier
    /// Converts bit selections to underscores: "signal[7]" -> "signal_7", "bus[10:5]" -> "bus_10_5"
    fn sanitize_wire_name(&self, wire_name: &str) -> String {
        let mut result = String::new();
        let mut in_bracket = false;
        
        for ch in wire_name.chars() {
            match ch {
                '[' => {
                    in_bracket = true;
                    result.push('_');
                }
                ']' => {
                    in_bracket = false;
                }
                ':' if in_bracket => {
                    result.push('_');
                }
                _ => {
                    result.push(ch);
                }
            }
        }
        
        result
    }
    
    /// 从信号表达式中提取主信号名（兼容旧接口）
    /// 例如："signal[7:0]" -> "signal"
    ///      "{a, b, c}" -> "" (拼接返回空，使用extract_signal_names代替)
    ///      "1'b0" -> "" (常量不处理)
    fn extract_signal_name(&self, signal_expr: &str) -> String {
        let signals = self.extract_signal_names(signal_expr);
        
        // 如果只有一个信号，返回它；否则返回空（表示拼接）
        if signals.len() == 1 {
            signals[0].clone()
        } else {
            String::new()
        }
    }
    
    /// 提取实例化段（排除端口、参数、信号声明等）
    fn extract_instance_section(&self, content: &str) -> String {
        let mut result = String::new();
        let lines: Vec<&str> = content.lines().collect();
        let mut in_port_list = false;
        let mut in_module_header = false;
        let mut paren_depth = 0;
        
        for (_line_num, line) in lines.iter().enumerate() {
            let trimmed = line.trim();
            
            // 跳过空行和注释
            if trimmed.is_empty() || trimmed.starts_with("/") {
                continue;
            }
            
            // 检测 module 声明开始
            if trimmed.starts_with("module ") {
                in_module_header = true;
                
                // 检查是否在同一行结束（如 module name(); ）
                if trimmed.ends_with(";") {
                    // 计算括号平衡
                    let open_count = trimmed.chars().filter(|&c| c == '(').count();
                    let close_count = trimmed.chars().filter(|&c| c == ')').count();
                    if open_count == close_count {
                        in_module_header = false;
                    }
                }
                continue;
            }
            
            // 在 module 头部，跟踪括号
            if in_module_header {
                for ch in trimmed.chars() {
                    if ch == '(' {
                        in_port_list = true;
                        paren_depth += 1;
                    } else if ch == ')' {
                        paren_depth -= 1;
                        if paren_depth == 0 {
                            in_port_list = false;
                        }
                    }
                }
                if trimmed.ends_with(";") && !in_port_list {
                    in_module_header = false;
                }
                continue;
            }
            
            // 跳过端口声明
            if trimmed.starts_with("input ") || trimmed.starts_with("output ") || 
               trimmed.starts_with("inout ") {
                continue;
            }
            
            // 跳过信号声明
            if trimmed.starts_with("wire ") || trimmed.starts_with("reg ") {
                continue;
            }
            
            // 跳过参数声明
            if trimmed.starts_with("parameter ") || trimmed.starts_with("localparam ") {
                continue;
            }
            
            // 跳过 assign 和 always 块
            if trimmed.starts_with("assign ") || trimmed.starts_with("always ") || 
               trimmed.starts_with("initial ") {
                continue;
            }
            
            // 跳过 endmodule
            if trimmed.starts_with("endmodule") {
                break;
            }
            
            // 其余内容可能是实例化
            result.push_str(line);
            result.push('\n');
        }
        
        result
    }
    
    /// 解析实例化语句（支持跨行、嵌套括号）
    /// 返回：(module_name, instance_name, attribute, port_connections)
    /// Build a line offset map for fast line number lookup
    /// Returns a vector where index i contains the character position where line i+1 starts
    fn build_line_map(&self, chars: &[char]) -> Vec<usize> {
        let mut line_offsets = vec![0]; // Line 1 starts at position 0
        for (i, &ch) in chars.iter().enumerate() {
            if ch == '\n' {
                line_offsets.push(i + 1); // Next line starts after the newline
            }
        }
        line_offsets
    }
    
    /// Fast line number lookup using binary search on pre-built line map
    /// Returns 1-based line number
    fn get_line_number(&self, line_map: &[usize], pos: usize) -> u32 {
        // Binary search to find which line this position belongs to
        match line_map.binary_search(&pos) {
            Ok(idx) => (idx + 1) as u32,  // Exact match - start of a line
            Err(idx) => idx as u32,        // Position is within line idx
        }
    }
    
    fn parse_instance_statements(&self, section: &str, original_content: &str) -> Vec<(String, String, String, u32, u32, Vec<PortConnection>)> {
        let mut instances = Vec::new();
        let chars: Vec<char> = section.chars().collect();
        let len = chars.len();
        
        // Build line offset map from ORIGINAL content for accurate absolute line numbers
        let original_chars: Vec<char> = original_content.chars().collect();
        let line_map = self.build_line_map(&original_chars);
        
        let mut i = 0;
        
        while i < len {
            // 跳过空白
            while i < len && chars[i].is_whitespace() {
                i += 1;
            }
            
            if i >= len {
                break;
            }
            
            // 检测条件编译
            if i + 6 < len && &chars[i..i+6] == &['`', 'i', 'f', 'd', 'e', 'f'] {
                // 先检查是否是跨越 `ifdef 的实例化模式
                // 即：`ifdef XXX ... `else module_name `endif instance_name (...)
                if let Some((inst, new_pos)) = self.parse_ifdef_instance(&chars, &line_map, i, original_content) {
                    instances.push(inst);
                    i = new_pos;
                    continue;
                }
                
                // 如果不是跨越 `ifdef 的实例化，则跳过整个 `ifdef 块
                // 因为 `ifdef 块内部可能是门级原语或其他非实例化语句
                if let Some(endif_pos) = self.find_keyword(&chars, i, "`endif") {
                    i = endif_pos + 6;  // 跳过 `endif
                    continue;
                }
            }
            
            // 尝试解析普通实例
            if let Some((inst, new_pos)) = self.parse_normal_instance(&chars, &line_map, i, original_content) {
                instances.push(inst);
                i = new_pos;
            } else {
                i += 1;
            }
        }
        
        instances
    }
    
    /// 解析 `ifdef 条件编译的实例
    /// 只处理跨越 `ifdef 的实例化模式：
    /// `ifdef XXX
    ///     module_a
    /// `else
    ///     module_b
    /// `endif
    /// #(...) instance_name (...);
    fn parse_ifdef_instance(&self, chars: &[char], line_map: &[usize], start: usize, original_content: &str) -> Option<((String, String, String, u32, u32, Vec<PortConnection>), usize)> {
        let len = chars.len();
        let mut i = start + 6; // 跳过 `ifdef
        
        // 跳过空白
        while i < len && chars[i].is_whitespace() {
            i += 1;
        }
        
        // 读取宏名
        let mut macro_name = String::new();
        while i < len && (chars[i].is_alphanumeric() || chars[i] == '_') {
            macro_name.push(chars[i]);
            i += 1;
        }
        
        // 查找 `else 和 `endif
        let else_pos = self.find_keyword(chars, i, "`else")?;
        let endif_pos = self.find_keyword(chars, else_pos, "`endif")?;
        
        // 检查 `endif 之后是否有实例名和端口列表
        // 如果没有，说明这不是跨越 `ifdef 的实例化模式
        let mut check_pos = endif_pos + 6;
        while check_pos < len && chars[check_pos].is_whitespace() {
            check_pos += 1;
        }
        
        // 跳过可能的参数列表
        if check_pos < len && chars[check_pos] == '#' {
            check_pos += 1;
            while check_pos < len && chars[check_pos].is_whitespace() {
                check_pos += 1;
            }
            if check_pos < len && chars[check_pos] == '(' {
                check_pos = self.skip_balanced_parens(chars, check_pos)?;
            }
            while check_pos < len && chars[check_pos].is_whitespace() {
                check_pos += 1;
            }
        }
        
        // 检查是否有实例名（以字母或下划线开头）
        if check_pos >= len || (!chars[check_pos].is_alphabetic() && chars[check_pos] != '_') {
            // 不是跨越 `ifdef 的实例化模式
            return None;
        }
        
        // 提取 else 分支的模块名
        let else_content: String = chars[else_pos + 5..endif_pos].iter().collect();
        let module_name = else_content.trim().to_string();
        
        // 检查模块名是否为门级原语
        if self.is_gate_primitive(&module_name) {
            return None;
        }
        
        // 查找实例名（在 `endif 之后）
        i = endif_pos + 6;
        
        // 跳过可能的参数列表和空白，找到实例名
        while i < len && chars[i].is_whitespace() {
            i += 1;
        }
        
        // 跳过参数列表（如果有）
        if i < len && chars[i] == '#' {
            i += 1;
            while i < len && chars[i].is_whitespace() {
                i += 1;
            }
            if i < len && chars[i] == '(' {
                i = self.skip_balanced_parens(chars, i)?;
            }
        }
        
        // 读取实例名
        while i < len && chars[i].is_whitespace() {
            i += 1;
        }
        
        let mut inst_name = String::new();
        while i < len && (chars[i].is_alphanumeric() || chars[i] == '_') {
            inst_name.push(chars[i]);
            i += 1;
        }
        
        // 跳过空白找到端口连接
        while i < len && chars[i].is_whitespace() {
            i += 1;
        }
        
        // 必须有端口连接 (...)
        if i >= len || chars[i] != '(' {
            return None;
        }
        
        // 解析端口连接
        let port_start = i;
        let port_end = self.find_matching_paren(chars, i)?;
        
        // Preprocess the port connection section to handle ifdef blocks
        let port_section: String = chars[port_start..=port_end].iter().collect();
        let preprocessed_port_section = self.preprocess_conditionals(&port_section);
        let preprocessed_chars: Vec<char> = preprocessed_port_section.chars().collect();
        
        // Build line map for port connections
        let port_line_map = self.build_line_map(&preprocessed_chars);
        
        // Parse port connections from preprocessed content
        let port_connections = self.parse_port_connections(&preprocessed_chars, &port_line_map, 0, preprocessed_chars.len() - 1);
        
        let mut end_pos = port_end + 1;  // 跳过端口连接段
        
        // 跳过空白
        while end_pos < len && chars[end_pos].is_whitespace() {
            end_pos += 1;
        }
        
        // 必须以分号结束
        if end_pos >= len || chars[end_pos] != ';' {
            return None;
        }
        
        end_pos += 1; // 跳过分号
        
        // Find absolute line numbers by searching in original content
        let (line_start, line_end) = self.find_instance_lines_in_original(original_content, &inst_name);
        
        if !module_name.is_empty() && !inst_name.is_empty() {
            let attribute = format!("ifdef:{}", macro_name);
            Some(((module_name, inst_name, attribute, line_start, line_end, port_connections), end_pos))
        } else {
            None
        }
    }
    
    /// Helper function to find instance line numbers in original content
    fn find_instance_lines_in_original(&self, original_content: &str, inst_name: &str) -> (u32, u32) {
        let lines: Vec<&str> = original_content.lines().collect();
        let mut start_line = 0u32;
        let mut end_line = 0u32;
        
        // Find the line where instance name appears
        for (idx, line) in lines.iter().enumerate() {
            if line.contains(inst_name) && (line.contains('(') || 
                (idx + 1 < lines.len() && lines[idx + 1].contains('('))) {
                start_line = (idx + 1) as u32;  // 1-based line number
                
                // Find the semicolon that ends the instance
                let mut found_end = false;
                for (end_idx, end_line_str) in lines[idx..].iter().enumerate() {
                    if end_line_str.contains(';') {
                        end_line = (idx + end_idx + 1) as u32;  // 1-based line number
                        found_end = true;
                        break;
                    }
                }
                
                if !found_end {
                    end_line = lines.len() as u32;
                }
                
                break;
            }
        }
        
        if start_line == 0 {
            // Fallback: if not found, return 1
            (1, 1)
        } else {
            (start_line, end_line)
        }
    }
    
    /// 解析普通实例（支持跨行和参数列表）
    fn parse_normal_instance(&self, chars: &[char], line_map: &[usize], start: usize, original_content: &str) -> Option<((String, String, String, u32, u32, Vec<PortConnection>), usize)> {
        let len = chars.len();
        let mut i = start;
        
        // 读取模块名
        let mut module_name = String::new();
        while i < len && (chars[i].is_alphanumeric() || chars[i] == '_') {
            module_name.push(chars[i]);
            i += 1;
        }
        
        // 检查是否为关键字或门级原语
        if module_name.is_empty() || self.is_keyword(&module_name) || self.is_gate_primitive(&module_name) {
            return None;
        }
        
        // 额外过滤: 如果模块名是 "end", "begin", "endcase" 等块结束符，也要过滤
        // 这些在真实项目中不会作为模块名，否则认为解析异常
        if matches!(module_name.as_str(), "end" | "begin" | "endcase" | "endgenerate" | "join" | "fork") {
            return None;
        }
        
        // 跳过空白
        while i < len && chars[i].is_whitespace() {
            i += 1;
        }
        
        // 检查是否有参数列表 #(...)
        if i < len && chars[i] == '#' {
            i += 1;
            while i < len && chars[i].is_whitespace() {
                i += 1;
            }
            if i < len && chars[i] == '(' {
                i = self.skip_balanced_parens(chars, i)?;
            }
        }
        
        // 跳过空白
        while i < len && chars[i].is_whitespace() {
            i += 1;
        }
        
        // 读取实例名
        let mut inst_name = String::new();
        while i < len && (chars[i].is_alphanumeric() || chars[i] == '_') {
            inst_name.push(chars[i]);
            i += 1;
        }
        
        // 检查实例名
        if inst_name.is_empty() || self.is_keyword(&inst_name) {
            return None;
        }
        
        // 跳过空白
        while i < len && chars[i].is_whitespace() {
            i += 1;
        }
        
        // 必须有端口连接 (...)
        if i >= len || chars[i] != '(' {
            return None;
        }
        
        // 解析端口连接（关键步骤）
        let port_start = i;
        let port_end = self.find_matching_paren(chars, i)?;
        
        // Preprocess the port connection section to handle ifdef blocks
        let port_section: String = chars[port_start..=port_end].iter().collect();
        let preprocessed_port_section = self.preprocess_conditionals(&port_section);
        let preprocessed_chars: Vec<char> = preprocessed_port_section.chars().collect();
        
        // Build line map for port connections  
        let port_line_map = self.build_line_map(&preprocessed_chars);
        
        // Parse port connections from preprocessed content
        let port_connections = self.parse_port_connections(&preprocessed_chars, &port_line_map, 0, preprocessed_chars.len() - 1);
        
        i = port_end + 1;  // 跳过端口连接段
        
        // 跳过空白
        while i < len && chars[i].is_whitespace() {
            i += 1;
        }
        
        // 必须以分号结束
        if i >= len || chars[i] != ';' {
            return None;
        }
        
        i += 1; // 跳过分号
        
        // Find absolute line numbers by searching in original content
        let (line_start, line_end) = self.find_instance_lines_in_original(original_content, &inst_name);
        
        Some(((module_name, inst_name, String::new(), line_start, line_end, port_connections), i))
    }
    
    /// 跳过平衡的括号（支持嵌套）
    fn skip_balanced_parens(&self, chars: &[char], start: usize) -> Option<usize> {
        let len = chars.len();
        let mut i = start;
        
        if i >= len || chars[i] != '(' {
            return None;
        }
        
        let mut depth = 0;
        while i < len {
            if chars[i] == '(' {
                depth += 1;
            } else if chars[i] == ')' {
                depth -= 1;
                if depth == 0 {
                    return Some(i + 1);
                }
            }
            i += 1;
        }
        
        None
    }
    
    /// 查找匹配的右括号位置
    fn find_matching_paren(&self, chars: &[char], start: usize) -> Option<usize> {
        let len = chars.len();
        let mut i = start;
        
        if i >= len || chars[i] != '(' {
            return None;
        }
        
        let mut depth = 0;
        while i < len {
            if chars[i] == '(' {
                depth += 1;
            } else if chars[i] == ')' {
                depth -= 1;
                if depth == 0 {
                    return Some(i);
                }
            }
            i += 1;
        }
        
        None
    }
    
    /// 解析端口连接（基于段分割的结构化方法）
    /// 支持各种复杂格式：拼接、位选择、常量、表达式
    fn parse_port_connections(&self, chars: &[char], line_map: &[usize], start: usize, end: usize) -> Vec<PortConnection> {
        let mut connections = Vec::new();
        let mut i = start + 1;  // 跳过左括号
        
        while i < end {
            // 跳过空白和换行
            while i < end && chars[i].is_whitespace() {
                i += 1;
            }
            
            if i >= end {
                break;
            }
            
            // 跳过注释 (//)
            if i + 1 < end && chars[i] == '/' && chars[i+1] == '/' {
                // 跳过到行尾
                while i < end && chars[i] != '\n' {
                    i += 1;
                }
                continue;
            }
            
            // 检测端口连接格式: .port_name(signal_expr)
            if chars[i] == '.' {
                let port_line_number = self.get_line_number(line_map, i);
                i += 1;  // 跳过 '.'
                
                // 读取端口名
                let mut port_name = String::new();
                while i < end && (chars[i].is_alphanumeric() || chars[i] == '_') {
                    port_name.push(chars[i]);
                    i += 1;
                }
                
                // 跳过空白
                while i < end && chars[i].is_whitespace() {
                    i += 1;
                }
                
                // 应该有左括号
                if i >= end || chars[i] != '(' {
                    break;
                }
                
                i += 1;  // 跳过 '('
                
                // 解析信号表达式（支持嵌套括号）
                let signal_start = i;
                let mut depth = 1;
                while i < end && depth > 0 {
                    if chars[i] == '(' {
                        depth += 1;
                    } else if chars[i] == ')' {
                        depth -= 1;
                    }
                    if depth > 0 {
                        i += 1;
                    }
                }
                
                let signal_expr: String = chars[signal_start..i].iter().collect();
                let signal_expr = signal_expr.trim().to_string();
                
                i += 1;  // 跳过右括号 ')'
                
                // 添加端口连接
                connections.push(PortConnection {
                    port_name,
                    signal_expr,
                    comment: String::new(),
                    line_number: port_line_number,
                });
                
                // 跳过逗号和空白
                while i < end && (chars[i].is_whitespace() || chars[i] == ',') {
                    i += 1;
                }
            } else {
                i += 1;
            }
        }
        
        connections
    }
    
    /// 查找关键字位置
    fn find_keyword(&self, chars: &[char], start: usize, keyword: &str) -> Option<usize> {
        let kw_chars: Vec<char> = keyword.chars().collect();
        let kw_len = kw_chars.len();
        let len = chars.len();
        
        for i in start..len {
            if i + kw_len <= len {
                let slice: Vec<char> = chars[i..i+kw_len].to_vec();
                if slice == kw_chars {
                    // For preprocessor keywords like `else, `elsif, `endif,
                    // make sure the next character is whitespace or end of input
                    // (not part of a longer identifier)
                    if keyword.starts_with('`') {
                        // For ` directives, check that what follows is not alphanumeric or underscore
                        let next_is_valid = if i + kw_len < len {
                            let next_char = chars[i + kw_len];
                            !next_char.is_alphanumeric() && next_char != '_'
                        } else {
                            true // End of input is OK
                        };
                        if next_is_valid {
                            return Some(i);
                        }
                    } else {
                        return Some(i);
                    }
                }
            }
        }
        
        None
    }
    
    /// 判断是否为 Verilog 结构关键字
    /// 只过滤绝对不可能作为模块名的关键字
    /// 注意: "end", "begin" 等可能是合法的模块名，不应过滤
    fn is_keyword(&self, word: &str) -> bool {
        matches!(
            word,
            "module" | "endmodule" | "input" | "output" | "inout" 
            | "wire" | "reg" | "assign" | "always" | "initial"
            | "parameter" | "localparam" | "defparam"
            | "if" | "else" | "case" | "casex" | "casez" | "default"
            | "for" | "while" | "repeat" | "forever"
            | "function" | "task" | "endfunction" | "endtask"
            | "generate" | "endgenerate"
        )
    }
    
    /// 判断是否为 Verilog 门级原语 (gate-level primitives)
    /// 这些不是模块实例化，而是 Verilog 内置的基本门电路
    fn is_gate_primitive(&self, word: &str) -> bool {
        matches!(
            word,
            // 基本逻辑门
            "and" | "nand" | "or" | "nor" | "xor" | "xnor" | "not" |
            // 缓冲器
            "buf" | "bufif0" | "bufif1" | "notif0" | "notif1" |
            // 三态门
            "tranif0" | "tranif1" | "tran" | "rtran" | "rtranif0" | "rtranif1" |
            // MOS 开关
            "nmos" | "pmos" | "cmos" | "rnmos" | "rpmos" | "rcmos" |
            // 上拉/下拉电阻
            "pullup" | "pulldown" | "pullupdown" |
            // 电源/地
            "supply0" | "supply1"
        )
    }
    
    /// Save database to file (static method)
    pub fn save_database_to_file(database: &ModbDatabase, path: &str) -> Result<()> {
        let mut buf = Vec::new();
        database.encode(&mut buf)?;
        fs::write(path, buf)?;
        Ok(())
    }
    
    /// Merge database to existing file (static method)
    pub fn merge_database_to_file(new_database: &ModbDatabase, path: &str) -> Result<()> {
        // Load existing database
        let data = fs::read(path)?;
        let mut existing_db = ModbDatabase::decode(&data[..])?;
        
        // Merge modules (avoid duplicates)
        let mut existing_names: HashSet<String> = existing_db.modules.iter()
            .map(|m| m.name.clone())
            .collect();
        
        for module in &new_database.modules {
            if !existing_names.contains(&module.name) {
                existing_db.modules.push(module.clone());
                existing_names.insert(module.name.clone());
            }
        }
        
        // Merge macros
        let mut existing_macro_names: HashSet<String> = existing_db.macros.iter()
            .map(|m| m.name.clone())
            .collect();
        
        for macro_def in &new_database.macros {
            if !existing_macro_names.contains(&macro_def.name) {
                existing_db.macros.push(macro_def.clone());
                existing_macro_names.insert(macro_def.name.clone());
            }
        }
        
        // Save merged database
        Self::save_database_to_file(&existing_db, path)?;
        Ok(())
    }

    /// 保存到 .modb 文件
    pub fn save_to_modb(&self, output_file: &str) -> Result<()> {
        let mut buf = Vec::new();
        self.database.encode(&mut buf)?;
        fs::write(output_file, buf)?;
        Ok(())
    }
    
    /// 从 .modb 文件加载
    pub fn load_from_modb(&mut self, modb_file: &str) -> Result<()> {
        let bytes = fs::read(modb_file)?;
        self.database = ModbDatabase::decode(&bytes[..])?;
        
        // 重建索引
        self.module_map.clear();
        for (idx, module) in self.database.modules.iter().enumerate() {
            self.module_map.insert(module.name.clone(), idx);
        }
        
        Ok(())
    }
    
    /// 合并到现有 .modb 文件
    pub fn merge_to_modb(&mut self, modb_file: &str) -> Result<()> {
        // Load existing database
        let bytes = fs::read(modb_file)?;
        let mut existing_db = ModbDatabase::decode(&bytes[..])?;
        
        // Merge modules: add new modules or update existing ones
        for new_module in &self.database.modules {
            // Check if module already exists
            if let Some(existing_module) = existing_db.modules.iter_mut().find(|m| m.name == new_module.name) {
                // Update existing module
                *existing_module = new_module.clone();
            } else {
                // Add new module
                existing_db.modules.push(new_module.clone());
            }
        }
        
        // Save merged database
        let mut buf = Vec::new();
        existing_db.encode(&mut buf)?;
        fs::write(modb_file, buf)?;
        
        Ok(())
    }
    
    /// 显示模块信息
    /// 
    /// # 参数
    /// * `module_name` - 模块名（None 表示显示所有模块）
    /// * `verbose` - 详细级别 (0: 简单, 1: -v 显示参数/端口/实例, 2: -vv 额外显示 wire)
    pub fn show_module_info(&self, module_name: Option<&str>, verbose: u8) {
        if let Some(name) = module_name {
            if let Some(&idx) = self.module_map.get(name) {
                let module = &self.database.modules[idx];
                self.print_module_info(module, verbose);
            } else {
                println!("Error: Module {} not found", name);
            }
        } else {
            for module in &self.database.modules {
                self.print_module_info(module, verbose);
                if verbose == 0 {
                    println!();
                }
            }
        }
    }
    
    /// 打印单个模块信息
    /// 
    /// # 参数
    /// * `module` - 模块数据
    /// * `verbose` - 详细级别 (0: 简单模式显示统计+实例列表, 1: -v 显示详细信息, 2: -vv 显示 wire)
    fn print_module_info(&self, module: &Module, verbose: u8) {
        println!("Module name: {}", module.name);
        
        if verbose >= 1 {
            println!("  Parameters ({}):", module.parameters.len());
            for param in &module.parameters {
                println!("    {} = {}", param.name, param.value);
            }
            
            println!("  Ports ({}):", module.ports.len());
            for port in &module.ports {
                let width_str = if port.width.is_empty() {
                    String::new()
                } else {
                    format!(" [{}]", port.width)
                };
                println!("    {} {}{}", port.direction, port.name, width_str);
            }
            
            // -vv 才显示 wire 信息
            if verbose >= 2 {
                println!("  Wires ({}):", module.wires.len());
                for wire in &module.wires {
                    let width_str = if wire.width.is_empty() {
                        String::new()
                    } else {
                        format!(" [{}]", wire.width)
                    };
                    println!("    {}{}", wire.name, width_str);
                }
            }
            
            println!("  Instances ({}):", module.instances.len());
            for inst in &module.instances {
                println!("    {} {}", inst.module_name, inst.name);
                if !inst.port_connections.is_empty() {
                    println!("      Port Connections ({}): ", inst.port_connections.len());
                    for conn in &inst.port_connections {
                        println!("        .{}({})", conn.port_name, conn.signal_expr);
                    }
                }
            }
        } else {
            // 简单模式：显示统计信息 + instance list
            let input_count = module.ports.iter().filter(|p| p.direction == "input").count();
            let output_count = module.ports.iter().filter(|p| p.direction == "output").count();
            let inout_count = module.ports.iter().filter(|p| p.direction == "inout").count();
            
            println!(
                "  Parameters: {}, Input ports: {}, Output ports: {}, Bidirectional ports: {}, Instance count: {}",
                module.parameters.len(),
                input_count,
                output_count,
                inout_count,
                module.instances.len()
            );
            
            // 显示 instance list
            if !module.instances.is_empty() {
                println!("  Instance list:");
                for inst in &module.instances {
                    println!("    {} {}", inst.module_name, inst.name);
                }
            }
        }
    }
    
    /// 显示模块层次结构
    /// 显示模块层次结构
    /// 
    /// # 参数
    /// * `module_name` - 模块名称
    /// * `max_level` - 最大显示层次深度 (0表示显示所有层次, 1表示只显示一层)
    /// * `output` - 输出CSV文件路径（可选）
    pub fn show_hierarchy(&self, module_name: &str, max_level: usize, output: Option<&str>) -> Result<()> {
        if let Some(&idx) = self.module_map.get(module_name) {
            let module = &self.database.modules[idx];
            
            if let Some(csv_path) = output {
                // CSV输出模式
                self.export_hierarchy_csv(module, module_name, max_level, csv_path)?;
                println!("Hierarchy exported to: {}", csv_path);
            } else {
                // 控制台输出模式
                println!("\nModule Hierarchy:");
                println!("{}", module.name);
                
                let mut visited = HashSet::new();
                visited.insert(module_name.to_string());
                
                self.print_hierarchy_recursive(module, "", true, &mut visited, 1, max_level);
            }
            Ok(())
        } else {
            Err(ParseError::ModuleNotFound(module_name.to_string()))
        }
    }
    
    /// 递归打印层次结构
    /// 
    /// # 参数
    /// * `module` - 当前模块
    /// * `prefix` - 打印前缀
    /// * `_is_last` - 是否为最后一个元素
    /// * `visited` - 已访问的模块集合，用于循环引用检测
    /// * `current_level` - 当前层次
    /// * `max_level` - 最大层次 (0表示无限制)
    fn print_hierarchy_recursive(
        &self,
        module: &Module,
        prefix: &str,
        _is_last: bool,
        visited: &mut HashSet<String>,
        current_level: usize,
        max_level: usize,
    ) {
        if module.instances.is_empty() {
            return;
        }
        
        // 检查是否超过最大层次
        if max_level > 0 && current_level > max_level {
            return;
        }
        
        let count = module.instances.len();
        for (i, inst) in module.instances.iter().enumerate() {
            let is_last_inst = i == count - 1;
            let branch = if is_last_inst { "└── " } else { "├── " };
            
            println!("{}{}{} ({})", prefix, branch, inst.name, inst.module_name);
            
            // 检查循环引用
            if visited.contains(&inst.module_name) {
                let new_prefix = format!("{}{}    ", prefix, if is_last_inst { " " } else { "│" });
                println!("{}└── {} [circular reference]", new_prefix, inst.module_name);
                continue;
            }
            
            // 递归显示子模块
            if let Some(&idx) = self.module_map.get(&inst.module_name) {
                let sub_module = &self.database.modules[idx];
                let new_prefix = format!("{}{}    ", prefix, if is_last_inst { " " } else { "│" });
                
                visited.insert(inst.module_name.clone());
                self.print_hierarchy_recursive(sub_module, &new_prefix, true, visited, current_level + 1, max_level);
                visited.remove(&inst.module_name);
            }
        }
    }
    
    /// 导出CSV格式的层次结构
    fn export_hierarchy_csv(
        &self,
        root_module: &Module,
        module_name: &str,
        max_level: usize,
        csv_path: &str,
    ) -> Result<()> {
        let mut rows: Vec<Vec<String>> = Vec::new();
        let mut visited = HashSet::new();
        visited.insert(module_name.to_string());
        
        // 添加顶层模块
        rows.push(vec![module_name.to_string()]);
        
        // 递归收集层次数据
        self.collect_hierarchy_rows(
            root_module,
            &mut rows,
            vec![module_name.to_string()],
            &mut visited,
            1,
            max_level,
        );
        
        // 写入CSV文件
        self.write_csv_file(csv_path, &rows)?;
        
        Ok(())
    }
    
    /// 递归收集层次数据（为CSV输出）
    fn collect_hierarchy_rows(
        &self,
        module: &Module,
        rows: &mut Vec<Vec<String>>,
        current_path: Vec<String>,
        visited: &mut HashSet<String>,
        current_level: usize,
        max_level: usize,
    ) {
        if module.instances.is_empty() {
            return;
        }
        
        // 检查是否超过最大层次
        if max_level > 0 && current_level > max_level {
            return;
        }
        
        for inst in &module.instances {
            // 创建新路径：前面的列只保留宏信息（attribute），不填充父模块信息
            let mut new_path = Vec::new();
            
            // 填充前面的列：只保留宏信息，其他为空
            for i in 0..current_path.len() {
                // 从 current_path 中提取信息
                let parent_info = &current_path[i];
                
                // 检查是否是宏信息（包含 ifdef/ifndef 或以 [ 开头）
                if parent_info.contains("ifdef:") || parent_info.contains("ifndef:") || 
                   (parent_info.starts_with("[") && parent_info.ends_with("]")) {
                    // 保留宏或特殊标记
                    new_path.push(parent_info.clone());
                } else {
                    // 不填充父模块信息，保持为空
                    new_path.push(String::new());
                }
            }
            
            // 添加当前实例名和模块名
            let inst_info = if inst.attribute.is_empty() {
                format!("{} ({})", inst.name, inst.module_name)
            } else {
                // 如果有宏信息，也显示出来
                format!("{} ({}) [{}]", inst.name, inst.module_name, inst.attribute)
            };
            new_path.push(inst_info);
            
            // 检查循环引用
            if visited.contains(&inst.module_name) {
                new_path.push("[循环引用]".to_string());
                rows.push(new_path);
                continue;
            }
            
            // 添加当前路径
            rows.push(new_path.clone());
            
            // 递归处理子模块
            if let Some(&idx) = self.module_map.get(&inst.module_name) {
                let sub_module = &self.database.modules[idx];
                
                visited.insert(inst.module_name.clone());
                self.collect_hierarchy_rows(
                    sub_module,
                    rows,
                    new_path,
                    visited,
                    current_level + 1,
                    max_level,
                );
                visited.remove(&inst.module_name);
            }
        }
    }
    
    /// 写入CSV文件
    fn write_csv_file(&self, csv_path: &str, rows: &[Vec<String>]) -> Result<()> {
        // 找出最大列数
        let max_cols = rows.iter().map(|r| r.len()).max().unwrap_or(0);
        
        // 构建CSV内容
        let mut csv_content = String::new();
        
        // 添加表头
        for i in 0..max_cols {
            if i > 0 {
                csv_content.push(',');
            }
            csv_content.push_str(&format!("Level_{}", i));
        }
        csv_content.push('\n');
        
        // 添加数据行
        for row in rows {
            for (i, cell) in row.iter().enumerate() {
                if i > 0 {
                    csv_content.push(',');
                }
                // 处理包含逗号或引号的单元格
                if cell.contains(',') || cell.contains('"') || cell.contains('\n') {
                    csv_content.push('"');
                    csv_content.push_str(&cell.replace('"', "\"\""));
                    csv_content.push('"');
                } else {
                    csv_content.push_str(cell);
                }
            }
            // 填充空列
            for _ in row.len()..max_cols {
                csv_content.push(',');
            }
            csv_content.push('\n');
        }
        
        // 写入文件
        fs::write(csv_path, csv_content)?;
        
        Ok(())
    }
    
    /// 获取数据库引用
    pub fn database(&self) -> &ModbDatabase {
        &self.database
    }
    
    /// 显示信号穿越关系（核心功能，类似Verdi的trace）
    pub fn show_signal_trace(
        &self,
        top_module: &str,
        from: Option<&str>,
        from_top: bool,
        feedthrough: &[String],
        to: Option<&str>,
        to_top: bool,
        tie: Option<&str>,
        verbose: bool,
        exclude: &[String],
        group: bool,
        source: Option<&str>,
        output: Option<&str>,
        debug: bool,
        sort: bool,
    ) -> Result<()> {
        // 获取顶层模块
        let top = self.database.modules.iter()
            .find(|m| m.name == top_module)
            .ok_or_else(|| ParseError::ModuleNotFound(top_module.to_string()))?;
        
        // 处理tie-off显示
        if let Some(tie_module) = tie {
            return self.show_tie_off_ports(top, tie_module);
        }
        
        // 确定from和to模块
        let from_module = if from_top {
            Some(top_module)
        } else {
            from
        };
        
        let to_module = if to_top {
            Some(top_module)
        } else {
            to
        };
        
        // 构建模块路径
        let mut module_path = Vec::new();
        if let Some(from_mod) = from_module {
            module_path.push(from_mod.to_string());
        }
        module_path.extend(feedthrough.iter().cloned());
        if let Some(to_mod) = to_module {
            module_path.push(to_mod.to_string());
        }
        
        if module_path.is_empty() {
            println!("Error: Need to specify signal path (use --from/--from-top or --to/--to-top)");
            return Ok(());
        }
        
        // 执行信号追踪
        self.trace_signals(top, &module_path, verbose, exclude, group, source, output, debug, sort)
    }
    
    /// 显示tie-off端口（绑定到常量的端口）
    fn show_tie_off_ports(&self, top_module: &Module, target_module: &str) -> Result<()> {
        println!("\nModule: {}", top_module.name);
        println!("Tie-off Port Analysis: {}", target_module);
        println!("{}", "=".repeat(100));
        
        // 查找目标实例
        let target_inst = top_module.instances.iter()
            .find(|i| i.name == target_module)
            .ok_or_else(|| ParseError::ModuleNotFound(format!("Submodule {} not found", target_module)))?;
        
        // 获取目标模块定义
        let target_mod_def = self.database.modules.iter()
            .find(|m| m.name == target_inst.module_name);
        
        // 构建端口名到连接信号的映射
        let mut port_to_signal: HashMap<String, String> = HashMap::new();
        for port_conn in &target_inst.port_connections {
            port_to_signal.insert(
                port_conn.port_name.clone(),
                port_conn.signal_expr.clone()
            );
        }
        
        // 构建顶层端口集合，用于检查连接是否到顶层端口
        let top_port_names: HashSet<String> = top_module.ports.iter()
            .map(|p| p.name.clone())
            .collect();
        
        // 显示表头
        println!("{:<30} | {:<15} | {:<10} | {:<30}", 
                 "端口名", "方向", "位宽", "Tie-off 值");
        println!("{}", "-".repeat(100));
        
        let mut tie_count = 0;
        let mut floating_count = 0;
        let mut total_ports = 0;
        
        // 如果有模块定义，使用定义中的端口信息
        if let Some(mod_def) = target_mod_def {
            total_ports = mod_def.ports.len();
            
            // 检查每个端口
            for port in &mod_def.ports {
                let mut tie_value = String::new();
                
                // 检查端口连接
                if let Some(signal_expr) = port_to_signal.get(&port.name) {
                    let signal_expr = signal_expr.trim();
                    
                    // 检查是否是常量
                    if self.is_constant_value(signal_expr) {
                        tie_value = signal_expr.to_string();
                        tie_count += 1;
                    } else if signal_expr.is_empty() {
                        // 空连接
                        if port.direction == "input" {
                            tie_value = "FLOATING".to_string();
                            floating_count += 1;
                        } else if port.direction == "output" {
                            tie_value = "UNCONNECTED".to_string();
                        }
                    } else {
                        // 检查是否连接到顶层端口
                        // 提取信号名（处理可能的拼接）
                        let connected_signals = self.extract_signal_names(signal_expr);
                        let connected_to_top_port = connected_signals.iter().any(|sig| top_port_names.contains(sig));
                        
                        // 如果连接到顶层端口，则不是tie-off
                        if connected_to_top_port {
                            // 不标记为tie-off，这是正常的连接
                        } else if signal_expr == "wire" {
                            // 特殊处理：如果信号表达式就是"wire"，这可能是解析错误
                            tie_value = "UNCONNECTED (Parse Error)".to_string();
                        }
                        // 其他情况是正常的信号连接，不显示
                    }
                } else {
                    // 端口未在 port_connections 中，说明未连接
                    if port.direction == "input" {
                        tie_value = "FLOATING".to_string();
                        floating_count += 1;
                    } else if port.direction == "output" {
                        tie_value = "UNCONNECTED".to_string();
                    }
                }
                
                // 只显示有tie-off或floating的端口
                // 跳过端口名为"wire"的情况，这通常是解析错误
                if !tie_value.is_empty() && port.name != "wire" {
                    let width_str = if port.width.is_empty() {
                        "1".to_string()
                    } else {
                        port.width.clone()
                    };
                    
                    println!("{:<30} | {:<15} | {:<10} | {:<30}", 
                             port.name, port.direction, width_str, tie_value);
                }
            }
        } else {
            // 没有模块定义，直接从 port_connections 分析
            println!("Warning: Module definition not found for {}, analysis based on port connections only\n", target_inst.module_name);
            total_ports = target_inst.port_connections.len();
            
            for port_conn in &target_inst.port_connections {
                let signal_expr = port_conn.signal_expr.trim();
                let mut tie_value = String::new();
                
                // 检查是否是常量
                if self.is_constant_value(signal_expr) {
                    tie_value = signal_expr.to_string();
                    tie_count += 1;
                } else if signal_expr.is_empty() {
                    tie_value = "FLOATING/UNCONNECTED".to_string();
                    floating_count += 1;
                } else {
                    // 检查是否连接到顶层端口
                    // 提取信号名（处理可能的拼接）
                    let connected_signals = self.extract_signal_names(signal_expr);
                    let connected_to_top_port = connected_signals.iter().any(|sig| top_port_names.contains(sig));
                    
                    // 如果连接到顶层端口，则不是tie-off
                    if connected_to_top_port {
                        // 不标记为tie-off，这是正常的连接
                    } else if signal_expr == "wire" {
                        // 特殊处理：如果信号表达式就是"wire"，这可能是解析错误
                        tie_value = "UNCONNECTED (Parse Error)".to_string();
                    }
                    // 其他情况是正常的信号连接，不显示
                }
                
                // 只显示有tie-off或floating的端口
                // 跳过端口名为"wire"的情况，这通常是解析错误
                if !tie_value.is_empty() && port_conn.port_name != "wire" {
                    println!("{:<30} | {:<15} | {:<10} | {:<30}", 
                             port_conn.port_name, "?", "?", tie_value);
                }
            }
        }
        
        println!("{}", "=".repeat(100));
        println!("Statistics: Tie-off: {}, Floating: {}, Total ports: {}", 
                 tie_count, floating_count, total_ports);
        println!();
        
        Ok(())
    }
    
    /// 判断是否为常量值
    fn is_constant_value(&self, name: &str) -> bool {
        lazy_static! {
            static ref CONST_REGEX: Regex = Regex::new(
                r"^(\d+'[bhdoBHDO][0-9a-fA-FxXzZ_]+|[01]|'[01]|'[bhdoBHDO][0-9a-fA-FxXzZ_]+)$"
            ).unwrap();
        }
        
        // First check if it matches the basic constant patterns
        if CONST_REGEX.is_match(name) {
            return true;
        }
        
        // Check for replication syntax like {4{signal}} which are constants
        // But exclude simple concatenations like {a, b}
        if name.starts_with('{') && name.ends_with('}') {
            let inner = &name[1..name.len()-1];
            // Check if it's replication syntax {n{...}}
            if inner.contains('{') && !inner.contains(',') {
                // This might be replication syntax, check if the part before first { is a number
                if let Some(first_brace) = inner.find('{') {
                    let count_part = &inner[..first_brace].trim();
                    if count_part.parse::<usize>().is_ok() {
                        return true;
                    }
                }
            }
            // Simple concatenations with commas are not constants
            // Replication without proper number prefix is not a constant
            return false;
        }
        
        false
    }
    
    /// Execute signal tracing
    fn trace_signals(&self, top_module: &Module, module_path: &[String], verbose: bool, exclude: &[String], group: bool, source: Option<&str>, output: Option<&str>, debug: bool, sort: bool) -> Result<()> {
        // Expand hierarchical paths to include intermediate steps
        let expanded_path = self.expand_hierarchical_path(module_path)?;
        
        println!("\nModule: {}", top_module.name);
        print!("Signal trace path: ");
        for (i, mod_name) in module_path.iter().enumerate() {
            if i > 0 {
                print!(" -> ");
            }
            print!("{}", mod_name);
        }
        println!("\n{}", "=".repeat(120));
        
        // Build column headers using expanded path
        let mut headers = Vec::new();
        for mod_name in &expanded_path {
            // Parse hierarchical path
            let parts: Vec<&str> = mod_name.split('.').collect();
            headers.push(parts.last().unwrap_or(&mod_name.as_str()).to_string());
        }
        
        // Trace signal connections using expanded path
        let connections = self.find_signal_connections(top_module, &expanded_path)?;
        
        // Determine if we need a wire column (only when there are exactly 2 modules in expanded path)
        let show_wire_column = expanded_path.len() == 2;
        
        // Calculate maximum signal length for each column
        let mut max_widths: Vec<usize> = headers.iter().map(|h| h.len()).collect();
        
        // Add wire column width if needed
        let mut wire_column_width: usize = 4; // Minimum width for "Wire" header
        
        // For all columns, calculate width based on formatted content
        for conn_chain in &connections {
            for (i, signal) in conn_chain.iter().enumerate() {
                if i < max_widths.len() && i < expanded_path.len() {
                    if i == 0 {
                        // For the first column, look up actual width and direction from top module
                        let (port_direction, port_width) = self.get_port_info(top_module, &expanded_path[i], signal);
                        let direction_abbr = self.get_direction_abbreviation(&port_direction);
                        let bit_count = self.calculate_bit_count(&port_width);
                        let width_str = if bit_count == 0 {
                            if !port_direction.is_empty() {
                                // Has direction but no width - single bit, don't show width
                                String::new()
                            } else {
                                "?".to_string()
                            }
                        } else if bit_count == 1 {
                            // Single-bit signals don't show width
                            String::new()
                        } else {
                            port_width.clone()
                        };
                        // Calculate actual display width: signal + space + [width] + space + direction
                        let display_width = if width_str.is_empty() {
                            signal.len() + 1 + direction_abbr.len()
                        } else {
                            signal.len() + 1 + width_str.len() + 1 + direction_abbr.len()
                        };
                        max_widths[i] = max_widths[i].max(display_width);
                    } else {
                        // For other columns, look up actual width from target module
                        let (port_direction, port_width) = self.get_port_info(top_module, &expanded_path[i], signal);
                        let direction_abbr = self.get_direction_abbreviation(&port_direction);
                        let bit_count = self.calculate_bit_count(&port_width);
                        let width_str = if bit_count == 0 {
                            if !port_direction.is_empty() {
                                // Has direction but no width - single bit, don't show width
                                String::new()
                            } else {
                                "?".to_string()
                            }
                        } else if bit_count == 1 {
                            // Single-bit signals don't show width
                            String::new()
                        } else {
                            port_width.clone()
                        };
                        // Calculate actual display width: signal + space + [width] + space + direction
                        let display_width = if width_str.is_empty() {
                            signal.len() + 1 + direction_abbr.len()
                        } else {
                            signal.len() + 1 + width_str.len() + 1 + direction_abbr.len()
                        };
                        max_widths[i] = max_widths[i].max(display_width);
                    }
                }
            }
        }
        
        // Calculate wire column width if needed
        if show_wire_column {
            for conn_chain in &connections {
                if conn_chain.len() >= 2 {
                    let to_port = &conn_chain[1];
                    if let Some(wire_name) = self.get_connecting_wire(top_module, &top_module.name, &expanded_path[1], to_port) {
                        wire_column_width = wire_column_width.max(wire_name.len());
                    }
                }
            }
            wire_column_width = wire_column_width.max(20); // Ensure minimum width
        }
        
        // Ensure minimum width of 20 characters per column
        for width in &mut max_widths {
            *width = (*width).max(20);
        }
        
        // Display table header (instance names)
        for (i, header) in headers.iter().enumerate() {
            if i > 0 {
                print!(" | ");
            }
            print!("{:<width$}", header, width = max_widths[i]);
        }
        // Add Wire column header if needed
        if show_wire_column {
            print!(" | ");
            print!("{:<width$}", "Wire", width = wire_column_width);
        }
        println!();
        
        // Display module names for each instance
        for (i, mod_name) in expanded_path.iter().enumerate() {
            if i > 0 {
                print!(" | ");
            }
            
            // Get the actual module type name using hierarchical path resolution
            let module_type_name = if mod_name == &top_module.name {
                // This is the top module itself
                top_module.name.clone()
            } else {
                // Try to resolve hierarchical path
                match self.resolve_hierarchical_path(top_module, mod_name) {
                    Ok((parent_module, inst_name)) => {
                        // Find the instance in the parent module and get its module_name
                        if let Some(inst) = parent_module.instances.iter().find(|inst| inst.name == inst_name) {
                            inst.module_name.clone()
                        } else {
                            "?".to_string()
                        }
                    },
                    Err(_) => {
                        // Fallback: try to find as direct instance in top_module
                        let parts: Vec<&str> = mod_name.split('.').collect();
                        let inst_name_ref = parts.last().copied().unwrap_or(mod_name.as_str());
                        if let Some(inst) = top_module.instances.iter().find(|inst| inst.name == inst_name_ref) {
                            inst.module_name.clone()
                        } else {
                            "?".to_string()
                        }
                    }
                }
            };
            
            print!("({:<width$})", module_type_name, width = max_widths[i] - 2);
        }
        // Add empty space for Wire column if needed
        if show_wire_column {
            print!(" | ");
            print!("{:<width$}", "", width = wire_column_width);
        }
        println!();
        
        // Display separator line
        for (i, width) in max_widths.iter().enumerate() {
            if i > 0 {
                print!(" + ");
            }
            print!("{}", "-".repeat(*width));
        }
        // Add separator for Wire column if needed
        if show_wire_column {
            print!(" + ");
            print!("{}", "-".repeat(wire_column_width));
        }
        println!();
        
        // Display connections with direction and width information
        if connections.is_empty() {
            println!("No signal connections found");
        } else {
            // Sort connections by direction if --sort is enabled
            let mut sorted_connections = connections.clone();
            if sort && !expanded_path.is_empty() {
                // Sort by the direction of the first column (source module)
                sorted_connections.sort_by(|a, b| {
                    if a.is_empty() || b.is_empty() {
                        return std::cmp::Ordering::Equal;
                    }
                    
                    let a_signal = &a[0];
                    let b_signal = &b[0];
                    
                    // Get direction for both signals
                    let (a_dir, _) = self.get_port_info(top_module, &expanded_path[0], a_signal);
                    let (b_dir, _) = self.get_port_info(top_module, &expanded_path[0], b_signal);
                    
                    // Define sort order: input(0) < output(1) < inout(2) < unknown(3)
                    let dir_order = |dir: &str| match dir {
                        "input" => 0,
                        "output" => 1,
                        "inout" => 2,
                        _ => 3,
                    };
                    
                    let a_order = dir_order(&a_dir);
                    let b_order = dir_order(&b_dir);
                    
                    // First sort by direction, then by signal name if directions are the same
                    match a_order.cmp(&b_order) {
                        std::cmp::Ordering::Equal => a_signal.cmp(b_signal),
                        other => other,
                    }
                });
            }
            
            let connections_to_display = if sort { &sorted_connections } else { &connections };
            
            // Track bit counts for summary
            let mut column_input_bits = vec![0u32; expanded_path.len()];
            let mut column_output_bits = vec![0u32; expanded_path.len()];
            let mut column_inout_bits = vec![0u32; expanded_path.len()];
            let mut column_unknown_count = vec![0u32; expanded_path.len()];
            
            // Keep track of processed signals to avoid duplicates
            let mut processed_signals: Vec<std::collections::HashSet<String>> = vec![std::collections::HashSet::new(); expanded_path.len()];
            
            // Track excluded signals for summary display
            let mut excluded_signals: Vec<String> = Vec::new();
            
            for conn_chain in connections_to_display {
                // Check if connection chain contains "---" (incomplete connection)
                let has_incomplete_connection = conn_chain.iter().any(|signal| signal == "---");
                
                if has_incomplete_connection {
                    continue; // Skip rows with incomplete connections
                }
                
                // Check if this connection should be excluded
                let should_exclude = if !conn_chain.is_empty() && !exclude.is_empty() {
                    let first_signal = &conn_chain[0];
                    exclude.iter().any(|pattern| first_signal.contains(pattern))
                } else {
                    false
                };
                
                if should_exclude {
                    // Collect excluded signal for summary
                    if !conn_chain.is_empty() {
                        let signal_name = &conn_chain[0];
                        if !excluded_signals.contains(signal_name) {
                            excluded_signals.push(signal_name.clone());
                        }
                    }
                    continue; // Skip this connection
                }
                
                // Process each connection chain
                if !conn_chain.is_empty() {
                    // Extract information for first column
                    let first_signal_name = &conn_chain[0];
                    
                    // Look up the direction and width - use get_port_info for consistency
                    let (first_direction, first_width) = self.get_port_info(top_module, &expanded_path[0], first_signal_name);
                    
                    // Check if we've already processed this signal in this column
                    if !processed_signals[0].contains(first_signal_name) {
                        processed_signals[0].insert(first_signal_name.to_string());
                        
                        // Get bit count for the signal
                        let bit_count = self.calculate_bit_count(&first_width);
                        // If bit_count is 0 but we have a direction, assume it's a 1-bit signal
                        let actual_bit_count = if bit_count == 0 && !first_direction.is_empty() {
                            1
                        } else {
                            bit_count
                        };
                        
                        match first_direction.as_str() {
                            "input" => column_input_bits[0] += actual_bit_count,
                            "output" => column_output_bits[0] += actual_bit_count,
                            "inout" => column_inout_bits[0] += actual_bit_count,
                            _ => {
                                // Unknown direction - count as unknown
                                column_unknown_count[0] += 1;
                            }
                        }
                    }
                    
                    let first_direction_abbr = self.get_direction_abbreviation(&first_direction);
                    
                    // Calculate width string for first column
                    let first_bit_count = self.calculate_bit_count(&first_width);
                    let first_width_str = if first_bit_count == 0 {
                        if !first_direction.is_empty() {
                            // Has direction but no width - single bit
                            String::new()
                        } else {
                            "?".to_string()
                        }
                    } else if first_bit_count == 1 {
                        // Single-bit signals don't show width
                        String::new()
                    } else {
                        // Width already includes brackets from parsing
                        first_width.clone()
                    };
                    
                    // Format first column: signal_name [width] direction with proper spacing
                    let total_first_col_width = max_widths[0];
                    let signal_with_width = if first_width_str.is_empty() {
                        first_signal_name.to_string()
                    } else {
                        format!("{} {}", first_signal_name, first_width_str)
                    };
                    // Calculate padding to right-align direction before |
                    let padding_needed = if signal_with_width.len() + 1 + first_direction_abbr.len() <= total_first_col_width {
                        total_first_col_width - signal_with_width.len() - first_direction_abbr.len()
                    } else {
                        1 // At least one space
                    };
                    print!("{}{:>width$}", signal_with_width, first_direction_abbr, width = padding_needed + first_direction_abbr.len());
                    print!(" |");
                    
                    // Print remaining columns
                    for i in 1..conn_chain.len() {
                        // Extract information for this column
                        let signal_name = &conn_chain[i];
                        
                        // Only format if within expanded_path bounds
                        if i < expanded_path.len() {
                            // Look up port information for this signal in the target module
                            let (port_direction, port_width) = self.get_port_info(top_module, &expanded_path[i], signal_name);
                            
                            // Check if we've already processed this signal in this column
                            if !processed_signals[i].contains(signal_name) {
                                processed_signals[i].insert(signal_name.to_string());
                                
                                // Get bit count for the signal
                                let bit_count = self.calculate_bit_count(&port_width);
                                // If bit_count is 0 but we have a direction, assume it's a 1-bit signal
                                let actual_bit_count = if bit_count == 0 && !port_direction.is_empty() {
                                    1
                                } else {
                                    bit_count
                                };
                                
                                match port_direction.as_str() {
                                    "input" => column_input_bits[i] += actual_bit_count,
                                    "output" => column_output_bits[i] += actual_bit_count,
                                    "inout" => column_inout_bits[i] += actual_bit_count,
                                    _ => {
                                        // Unknown direction - count as unknown
                                        column_unknown_count[i] += 1;
                                    }
                                }
                            }
                            
                            // Format: signal_name [width] direction with proper alignment
                            let bit_count = self.calculate_bit_count(&port_width);
                            let width_str = if bit_count == 0 {
                                if !port_direction.is_empty() {
                                    // Has direction but no width - single bit
                                    String::new()
                                } else {
                                    "?".to_string()
                                }
                            } else if bit_count == 1 {
                                // For single-bit signals, don't show width
                                String::new()
                            } else {
                                // Width already includes brackets from parsing
                                port_width.clone()
                            };
                            let direction_abbr = self.get_direction_abbreviation(&port_direction);
                            
                            // Format: signal_name [width] direction with proper spacing
                            let total_col_width = max_widths[i];
                            let signal_with_width = if width_str.is_empty() {
                                signal_name.to_string()
                            } else {
                                format!("{} {}", signal_name, width_str)
                            };
                            // Calculate padding to right-align direction before separator
                            let padding_needed = if signal_with_width.len() + 1 + direction_abbr.len() <= total_col_width {
                                total_col_width - signal_with_width.len() - direction_abbr.len()
                            } else {
                                1 // At least one space
                            };
                            print!(" {}{:>width$}", signal_with_width, direction_abbr, width = padding_needed + direction_abbr.len());
                            
                            // Add separator between columns (except for the last one)
                            if i < expanded_path.len() - 1 {
                                print!(" |");
                            }
                        }
                    }
                    
                    // Add Wire column at the end if needed (for 2 modules)
                    if show_wire_column && conn_chain.len() >= 2 {
                        let to_port = &conn_chain[1];
                        let wire_name = self.get_connecting_wire(top_module, &top_module.name, &expanded_path[1], to_port)
                            .unwrap_or_else(|| "".to_string());
                        print!(" | ");
                        print!("{:<width$}", wire_name, width = wire_column_width);
                    }
                }
                println!();
                
                // In verbose mode, print wire names below the ports
                if verbose && !conn_chain.is_empty() && expanded_path.len() > 2 {
                    // For multi-level hierarchies, print wire names on a separate row
                    let mut wire_names: Vec<String> = vec![String::new(); expanded_path.len()];
                    
                    // For each column (except the last one), get the wire connecting it to the next column
                    for i in 0..expanded_path.len() - 1 {
                        if i + 1 < conn_chain.len() {
                            let next_port_name = &conn_chain[i + 1];
                            
                            // Determine which module context to use for wire lookup
                            let parent_path = if i == 0 {
                                // For first transition, use top module
                                top_module.name.clone()
                            } else {
                                // For other transitions, use the previous instance path
                                expanded_path[i].clone()
                            };
                            
                            let next_module_path = &expanded_path[i + 1];
                            
                            // Get the wire name
                            if let Some(wire_name) = self.get_connecting_wire(top_module, &parent_path, next_module_path, next_port_name) {
                                wire_names[i] = format!(" \\_ {}", wire_name);
                            }
                        }
                    }
                    
                    // Print wire row if any wires exist
                    if wire_names.iter().any(|w| !w.is_empty()) {
                        for i in 0..expanded_path.len() {
                            if i > 0 {
                                print!(" | ");
                            }
                            print!("{:<width$}", wire_names[i], width = max_widths[i]);
                        }
                        println!();
                    }
                }
            }
            
            // Display bit count summary in the requested format
            // First, display the separator line matching the column structure
            for (i, width) in max_widths.iter().enumerate() {
                if i > 0 {
                    print!(" + ");
                }
                print!("{}", "-".repeat(*width));
            }
            // Add separator for Wire column if needed
            if show_wire_column {
                print!(" + ");
                print!("{}", "-".repeat(wire_column_width));
            }
            println!();
            
            println!("Bits Summary:");
            
            // Use fixed width for labels to ensure vertical alignment of | separators
            let label_width = 10; // "  Unknown:" is 10 chars, the longest label
            
            // Print input bits
            print!("{:<width$}", "  Input:", width = label_width);
            for i in 0..module_path.len() {
                if i > 0 {
                    print!(" | ");
                }
                if i == 0 {
                    print!("{:<width$}", column_input_bits[i], width = max_widths[i] - label_width);
                } else {
                    print!("{:<width$}", column_input_bits[i], width = max_widths[i]);
                }
            }
            // Add empty space for Wire column if needed
            if show_wire_column {
                print!(" | ");
                print!("{:<width$}", "", width = wire_column_width);
            }
            println!();
            
            // Print output bits
            print!("{:<width$}", "  Output:", width = label_width);
            for i in 0..module_path.len() {
                if i > 0 {
                    print!(" | ");
                }
                if i == 0 {
                    print!("{:<width$}", column_output_bits[i], width = max_widths[i] - label_width);
                } else {
                    print!("{:<width$}", column_output_bits[i], width = max_widths[i]);
                }
            }
            // Add empty space for Wire column if needed
            if show_wire_column {
                print!(" | ");
                print!("{:<width$}", "", width = wire_column_width);
            }
            println!();
            
            // Print inout bits
            print!("{:<width$}", "  Inout:", width = label_width);
            for i in 0..module_path.len() {
                if i > 0 {
                    print!(" | ");
                }
                if i == 0 {
                    print!("{:<width$}", column_inout_bits[i], width = max_widths[i] - label_width);
                } else {
                    print!("{:<width$}", column_inout_bits[i], width = max_widths[i]);
                }
            }
            // Add empty space for Wire column if needed
            if show_wire_column {
                print!(" | ");
                print!("{:<width$}", "", width = wire_column_width);
            }
            println!();
            
            // Print unknown count
            print!("{:<width$}", "  Unknown:", width = label_width);
            for i in 0..module_path.len() {
                if i > 0 {
                    print!(" | ");
                }
                if i == 0 {
                    print!("{:<width$}", column_unknown_count[i], width = max_widths[i] - label_width);
                } else {
                    print!("{:<width$}", column_unknown_count[i], width = max_widths[i]);
                }
            }
            // Add empty space for Wire column if needed
            if show_wire_column {
                print!(" | ");
                print!("{:<width$}", "", width = wire_column_width);
            }
            println!();
            
            // Display excluded signals if any
            if !excluded_signals.is_empty() {
                println!();
                println!("Excluded Signals ({}):", excluded_signals.len());
                for (i, signal) in excluded_signals.iter().enumerate() {
                    if i > 0 {
                        print!(", ");
                    }
                    print!("{}", signal);
                }
                println!();
            }
        }
        
        // Display bottom separator
        for (i, width) in max_widths.iter().enumerate() {
            if i > 0 {
                print!(" + ");
            }
            print!("{}", "=".repeat(*width));
        }
        // Add separator for Wire column if needed
        if show_wire_column {
            print!(" + ");
            print!("{}", "=".repeat(wire_column_width));
        }
        println!("\n");
        
        // Generate grouped assign statements if -g mode is enabled
        if group && module_path.len() == 2 {
            self.generate_grouped_assigns(top_module, module_path, &connections, exclude)?;
            
            // If source and output files are specified, perform feedthrough modification
            if let (Some(source_file), Some(output_file)) = (source, output) {
                self.apply_feedthrough_modification(
                    top_module,
                    module_path,
                    &connections,
                    exclude,
                    source_file,
                    output_file,
                    debug,
                )?;
            }
        }
        
        Ok(())
    }
    
    /// Generate grouped assign statements for -g mode
    fn generate_grouped_assigns(
        &self,
        top_module: &Module,
        module_path: &[String],
        connections: &[Vec<String>],
        exclude: &[String],
    ) -> Result<()> {
        println!("// Verilog assign statements:");
        println!();
        
        // Collect signal information with direction validation
        #[derive(Clone)]
        struct SignalInfo {
            from_port: String,
            to_port: String,
            wire_name: String,
            from_direction: String,
            to_direction: String,
            port_width: String,  // Use port width instead of wire width
        }
        
        let mut output_to_input: Vec<SignalInfo> = Vec::new();
        let mut input_to_output: Vec<SignalInfo> = Vec::new();
        let mut warnings: Vec<String> = Vec::new();
        
        for conn_chain in connections {
            if conn_chain.len() < 2 {
                continue;
            }
            
            // Check exclusion
            let should_exclude = if !exclude.is_empty() {
                let first_signal = &conn_chain[0];
                exclude.iter().any(|pattern| first_signal.contains(pattern))
            } else {
                false
            };
            
            if should_exclude {
                continue;
            }
            
            let from_port = &conn_chain[0];
            let to_port = &conn_chain[1];
            
            // Get port information and directions
            let (from_direction, from_width) = self.get_port_info(top_module, &module_path[0], from_port);
            let (to_direction, to_width) = self.get_port_info(top_module, &module_path[1], to_port);
            
            // Get the connecting wire name (use top module as context)
            let wire_name = self.get_connecting_wire(top_module, &top_module.name, &module_path[1], to_port)
                .unwrap_or_else(|| format!("wire_{}_to_{}", from_port, to_port));
            
            // Calculate actual wire width from wire_name (considering bit selection)
            let actual_wire_width = self.calculate_wire_actual_width(&wire_name, &to_width);
            
            // Use the actual wire width for bit counting
            let port_width = actual_wire_width;
            
            let signal_info = SignalInfo {
                from_port: from_port.clone(),
                to_port: to_port.clone(),
                wire_name,
                from_direction: from_direction.clone(),
                to_direction: to_direction.clone(),
                port_width,
            };
            
            // Categorize by direction with validation
            match (from_direction.as_str(), to_direction.as_str()) {
                ("output", "input") => output_to_input.push(signal_info),
                ("input", "output") => input_to_output.push(signal_info),
                ("output", "output") => {
                    warnings.push(format!("Warning: output->output connection: {} -> {}", from_port, to_port));
                }
                ("input", "input") => {
                    warnings.push(format!("Warning: input->input connection: {} -> {}", from_port, to_port));
                }
                ("inout", _) | (_, "inout") => {
                    output_to_input.push(signal_info); // Treat inout as bidirectional
                }
                _ => {
                    // Unknown directions - add to output_to_input as default
                    output_to_input.push(signal_info);
                }
            }
        }
        
        // Display warnings if any
        for warning in &warnings {
            println!("// {}", warning);
        }
        if !warnings.is_empty() {
            println!();
        }
        
        // Convert to tuple format for print_assign_block
        let output_to_input_tuples: Vec<(String, String, String, String, String, String)> = output_to_input.iter()
            .map(|s| (s.from_port.clone(), s.to_port.clone(), s.wire_name.clone(), s.from_direction.clone(), s.to_direction.clone(), s.port_width.clone()))
            .collect();
        let input_to_output_tuples: Vec<(String, String, String, String, String, String)> = input_to_output.iter()
            .map(|s| (s.from_port.clone(), s.to_port.clone(), s.wire_name.clone(), s.from_direction.clone(), s.to_direction.clone(), s.port_width.clone()))
            .collect();
        
        // Generate output->input assigns
        if !output_to_input_tuples.is_empty() {
            self.print_assign_block(
                module_path,
                &output_to_input_tuples,
                "output",
                "input",
            );
            println!();
        }
        
        // Generate input->output assigns
        if !input_to_output_tuples.is_empty() {
            self.print_assign_block(
                module_path,
                &input_to_output_tuples,
                "input",
                "output",
            );
        }
        
        Ok(())
    }
    
    /// Print a block of assign statements for a specific direction
    fn print_assign_block(
        &self,
        module_path: &[String],
        signals: &[(String, String, String, String, String, String)],  // (from_port, to_port, wire_name, from_dir, to_dir, width)
        from_dir: &str,
        to_dir: &str,
    ) {
        if signals.is_empty() {
            return;
        }
        
        // Extract instance names for FT signal naming
        let from_inst_parts: Vec<&str> = module_path[0].split('.').collect();
        let to_inst_parts: Vec<&str> = module_path[1].split('.').collect();
        let from_inst_name = from_inst_parts.last().copied().unwrap_or(module_path[0].as_str());
        let to_inst_name = to_inst_parts.last().copied().unwrap_or(module_path[1].as_str());
        
        let ft_in_signal = format!("FT_IN_{}_to_{}", from_inst_name, to_inst_name);
        let ft_out_signal = format!("FT_OUT_{}_to_{}", from_inst_name, to_inst_name);
        
        // Calculate total bit width for FT signal
        let mut total_bits = 0u32;
        for (_, _, _, _, _, width) in signals {
            let bit_count = self.calculate_bit_count(width);
            total_bits += if bit_count == 0 { 1 } else { bit_count };
        }
        
        println!("// {} -> {} connections", from_dir, to_dir);
        
        // Calculate max width for alignment
        let mut max_width_str_len = 0;
        for (_, _, _, _, _, width) in signals {
            let bit_count = self.calculate_bit_count(width);
            if bit_count > 1 {
                max_width_str_len = max_width_str_len.max(width.len());
            }
        }
        
        // Declare FT_IN signal wire before first assign
        let ft_width = if total_bits > 1 {
            format!("[{}:0]", total_bits - 1)
        } else {
            String::new()
        };
        
        if !ft_width.is_empty() {
            println!("// wire {:<width$} {};", ft_width, ft_in_signal, width = max_width_str_len);
        } else {
            println!("// wire {};", ft_in_signal);
        }
        println!();
        
        // First assign: source wires to FT_IN signal (uses existing wires)
        println!("assign {} = {{", ft_in_signal);
        
        // Calculate bit positions from RIGHT to LEFT (last signal is LSB at position 0)
        let mut cumulative_bits = 0u32;
        let mut bit_positions: Vec<(u32, u32)> = Vec::new(); // (start_bit, end_bit) for each signal
        
        // First pass: calculate positions from right to left (reverse order)
        for (_, _, _, _, _, width) in signals.iter().rev() {
            let bit_count = self.calculate_bit_count(width);
            let actual_bit_count = if bit_count == 0 { 1 } else { bit_count };
            
            let start_bit = cumulative_bits;
            let end_bit = cumulative_bits + actual_bit_count - 1;
            
            bit_positions.push((start_bit, end_bit));
            cumulative_bits += actual_bit_count;
        }
        
        // Reverse to match original signal order
        bit_positions.reverse();
        
        // Second pass: print signals with correct bit positions
        for (i, ((_, _, wire_name, _, _, _), (start_bit, end_bit))) in signals.iter().zip(bit_positions.iter()).enumerate() {
            let width = end_bit - start_bit + 1;
            let bit_comment = if width > 1 {
                format!(" // [{}:{}]", end_bit, start_bit)
            } else {
                format!(" // [{}]", start_bit)
            };
            
            if i < signals.len() - 1 {
                println!("    {},{}", wire_name, bit_comment);
            } else {
                println!("    {}{}", wire_name, bit_comment);
            }
        }
        println!("}};\n");
        
        // Wire declarations for second assign (FT_OUT and individual FT_ wires)
        // Declare FT_OUT signal wire
        if !ft_width.is_empty() {
            println!("// wire {:<width$} {};", ft_width, ft_out_signal, width = max_width_str_len);
        } else {
            println!("// wire {};", ft_out_signal);
        }
        
        // Declare individual wires with FT_ prefix
        for (_, _, wire_name, _, _, width) in signals {
            let bit_count = self.calculate_bit_count(width);
            let width_str = if bit_count > 1 {
                width.clone()
            } else {
                String::new()
            };
            
            // Sanitize wire name to be valid Verilog identifier
            let sanitized_wire = self.sanitize_wire_name(wire_name);
            let ft_wire_name = format!("FT_{}", sanitized_wire);
            
            if !width_str.is_empty() {
                println!("wire {:<width$} {};", width_str, ft_wire_name, width = max_width_str_len);
            } else {
                println!("wire {};", ft_wire_name);
            }
        }
        println!();
        
        // Second assign: FT_OUT signal to target ports
        println!("assign {{");
        
        // Calculate bit positions from RIGHT to LEFT (last signal is LSB at position 0)
        let mut cumulative_bits = 0u32;
        let mut bit_positions: Vec<(u32, u32)> = Vec::new(); // (start_bit, end_bit) for each signal
        
        // First pass: calculate positions from right to left (reverse order)
        for (_, _, _, _, _, width) in signals.iter().rev() {
            let bit_count = self.calculate_bit_count(width);
            let actual_bit_count = if bit_count == 0 { 1 } else { bit_count };
            
            let start_bit = cumulative_bits;
            let end_bit = cumulative_bits + actual_bit_count - 1;
            
            bit_positions.push((start_bit, end_bit));
            cumulative_bits += actual_bit_count;
        }
        
        // Reverse to match original signal order
        bit_positions.reverse();
        
        // Second pass: print signals with correct bit positions
        for (i, ((_, _, wire_name, _, _, _), (start_bit, end_bit))) in signals.iter().zip(bit_positions.iter()).enumerate() {
            let width = end_bit - start_bit + 1;
            let bit_comment = if width > 1 {
                format!(" // [{}:{}]", end_bit, start_bit)
            } else {
                format!(" // [{}]", start_bit)
            };
            
            // Sanitize wire name to be valid Verilog identifier
            let sanitized_wire = self.sanitize_wire_name(wire_name);
            let ft_wire_name = format!("FT_{}", sanitized_wire);
            
            if i < signals.len() - 1 {
                println!("    {},{}", ft_wire_name, bit_comment);
            } else {
                println!("    {}{}", ft_wire_name, bit_comment);
            }
        }
        println!("}} = {};\n", ft_out_signal);
    }
    
    /// Locate instance in source file using line_number hints with fallback strategies
    /// 
    /// Returns: Option<(start_line, end_line)> where lines are 0-based indices
    /// 
    /// Strategy:
    /// 1. Try using line_number hints (absolute file line numbers)
    /// 2. Search nearby range (±20 lines)
    /// 3. Full file search as last resort
    fn locate_instance_in_source(
        &self,
        file_lines: &[&str],
        inst_name: &str,
        line_hint: Option<(usize, usize)>,
    ) -> Option<(usize, usize)> {
        // Strategy 1: Try using line_number hints (absolute file line numbers)
        if let Some((start_hint, end_hint)) = line_hint {
            // Verify the hint by checking if instance name appears near the hinted line
            let search_start = start_hint.saturating_sub(1).max(0);
            let search_end = (end_hint + 1).min(file_lines.len());
            
            for i in search_start..search_end {
                let line = file_lines[i].trim();
                if line.contains(inst_name) {
                    // Check if opening paren is on same line
                    if line.contains('(') {
                        if let Some(end_idx) = self.find_instance_end(file_lines, i) {
                            println!("// Located instance '{}' at lines {}-{} (using line_number hint)", 
                                    inst_name, i + 1, end_idx + 1);
                            return Some((i, end_idx));
                        }
                    } else {
                        // Check next few lines for opening paren
                        for j in (i+1)..((i+5).min(file_lines.len())) {
                            if file_lines[j].trim().contains('(') {
                                if let Some(end_idx) = self.find_instance_end(file_lines, j) {
                                    println!("// Located instance '{}' at lines {}-{} (using line_number hint - multi-line)", 
                                            inst_name, i + 1, end_idx + 1);
                                    return Some((i, end_idx));
                                }
                            }
                        }
                    }
                }
            }
            
            println!("// Line_number hint {}-{} didn't find instance '{}', searching nearby...", 
                    start_hint, end_hint, inst_name);
            
            // Strategy 2: Search in a wider range around the hint (±20 lines)
            let wider_start = start_hint.saturating_sub(20).max(0);
            let wider_end = (end_hint + 20).min(file_lines.len());
            
            for i in wider_start..wider_end {
                let line = file_lines[i].trim();
                if line.contains(inst_name) {
                    // Check if opening paren is on same line
                    if line.contains('(') {
                        if let Some(end_idx) = self.find_instance_end(file_lines, i) {
                            println!("// Located instance '{}' at lines {}-{} (nearby search)", 
                                    inst_name, i + 1, end_idx + 1);
                            return Some((i, end_idx));
                        }
                    } else {
                        // Check next few lines for opening paren
                        for j in (i+1)..((i+5).min(file_lines.len())) {
                            if file_lines[j].trim().contains('(') {
                                if let Some(end_idx) = self.find_instance_end(file_lines, j) {
                                    println!("// Located instance '{}' at lines {}-{} (nearby search - multi-line)", 
                                            inst_name, i + 1, end_idx + 1);
                                    return Some((i, end_idx));
                                }
                            }
                        }
                    }
                }
            }
        }
        
        // Strategy 3: Full file search as last resort
        println!("// Searching entire file for instance '{}'...", inst_name);
        
        for i in 0..file_lines.len() {
            let line = file_lines[i].trim();
            
            // Check if this line contains the instance name
            // Pattern 1: instance_name on same line with (
            if (line.contains(&format!(" {}", inst_name)) || line.starts_with(inst_name)) {
                // Check if opening paren is on same line
                if line.contains('(') {
                    // Found instance start on same line
                    if let Some(end_idx) = self.find_instance_end(file_lines, i) {
                        println!("// Located instance '{}' at lines {}-{} (full file search - same line)", 
                                inst_name, i + 1, end_idx + 1);
                        return Some((i, end_idx));
                    }
                } else {
                    // Pattern 2: instance_name on separate line, check next few lines for (
                    // This handles cases like:
                    // `ifdef ... `endif
                    // instance_name(
                    for j in (i+1)..((i+5).min(file_lines.len())) {
                        let next_line = file_lines[j].trim();
                        if next_line.contains('(') {
                            // Found opening paren, this is the instance start
                            if let Some(end_idx) = self.find_instance_end(file_lines, j) {
                                println!("// Located instance '{}' at lines {}-{} (full file search - multi-line)", 
                                        inst_name, i + 1, end_idx + 1);
                                return Some((i, end_idx));
                            }
                        }
                        // Stop if we hit another potential instance or module keyword
                        if next_line.contains("module ") || (next_line.contains(' ') && next_line.contains('(') && !next_line.starts_with('.')) {
                            break;
                        }
                    }
                }
            }
        }
        
        println!("// Warning: Could not locate instance '{}' in file", inst_name);
        None
    }
    
    /// Find the end line of an instance starting at start_idx
    /// Returns the 0-based line index of the line containing the closing `);
    fn find_instance_end(&self, file_lines: &[&str], start_idx: usize) -> Option<usize> {
        let mut depth = 0;
        let mut in_parens = false;
        
        for j in start_idx..file_lines.len() {
            let line = file_lines[j];
            if line.contains('(') {
                in_parens = true;
            }
            if in_parens {
                for c in line.chars() {
                    if c == '(' { depth += 1; }
                    else if c == ')' { depth -= 1; }
                }
            }
            if in_parens && depth == 0 && line.contains(';') {
                return Some(j);
            }
        }
        None
    }
    
    /// Locate a specific port connection line within an instance range
    /// 
    /// Returns: Option<line_index> where line_index is 0-based
    /// 
    /// Searches for `.port_name(signal_expr)` pattern with three fallback strategies:
    /// 1. Within the instance range
    /// 2. Full file search if instance range fails
    /// 
    /// # Example
    /// ```rust
    /// // After locating instance range (9, 14)
    /// let port_line = self.locate_port_in_instance(&lines, (9, 14), "data_out", "u_inst", true);
    /// // Returns: Some(12) if .data_out() is found at line 12
    /// ```
    fn locate_port_in_instance(
        &self,
        file_lines: &[&str],
        instance_range: (usize, usize),
        port_name: &str,
        instance_name: &str,
        enable_fallback: bool,
    ) -> Option<usize> {
        let (start, end) = instance_range;
        let port_pattern = format!(".{}", port_name);
        
        // Strategy 1: Search within instance range
        for i in start..=end {
            if i < file_lines.len() && file_lines[i].contains(&port_pattern) {
                return Some(i);
            }
        }
        
        // Strategy 2: If fallback enabled and not found, search the entire file
        if enable_fallback {
            println!("//   Port '{}' not found in instance range, searching entire file...", port_name);
            for i in 0..file_lines.len() {
                if file_lines[i].contains(&port_pattern) {
                    // Check if this line is likely within an instance named instance_name
                    // by looking backwards for the instance declaration
                    let mut found_instance = false;
                    for j in (0..=i).rev() {
                        if file_lines[j].contains(&format!("{} ", instance_name)) ||
                           file_lines[j].contains(&format!("{}(", instance_name)) {
                            found_instance = true;
                            break;
                        }
                        // Stop if we hit another instance or module
                        if file_lines[j].contains(" u_") && file_lines[j].contains('(') {
                            break;
                        }
                    }
                    if found_instance {
                        println!("//   Found port '{}' at line {} (full file search)", port_name, i + 1);
                        return Some(i);
                    }
                }
            }
            println!("//   Port '{}' not found even in full file search", port_name);
        }
        
        None
    }
    
    /// Generate feedthrough wire declarations and assign statements
    /// 
    /// Returns: (verilog_code: String, replacement_map: HashMap<String, String>)
    /// 
    /// The first assign uses original wire names (no FT_ prefix)
    /// The second assign uses FT_ prefixed wire names
    fn generate_feedthrough_code(
        &self,
        output_to_input: &[SignalInfo],
        from_inst_name: &str,
        to_inst_name: &str,
    ) -> (String, HashMap<String, String>) {
        let mut verilog_code = String::new();
        let mut replacement_map: HashMap<String, String> = HashMap::new();
        
        let ft_in_signal = format!("FT_IN_{}_to_{}", from_inst_name, to_inst_name);
        let ft_out_signal = format!("FT_OUT_{}_to_{}", from_inst_name, to_inst_name);
        
        // Calculate total bit width
        let mut total_bits = 0u32;
        for signal_info in output_to_input {
            let bit_count = self.calculate_bit_count(&signal_info.port_width);
            total_bits += if bit_count == 0 { 1 } else { bit_count };
        }
        
        let ft_width = if total_bits > 1 {
            format!("[{}:0]", total_bits - 1)
        } else {
            String::new()
        };
        
        // Wire declaration for FT_IN
        if !ft_width.is_empty() {
            verilog_code.push_str(&format!("// wire {} {};\n", ft_width, ft_in_signal));
        } else {
            verilog_code.push_str(&format!("// wire {};\n", ft_in_signal));
        }
        verilog_code.push_str("\n");
        
        // First assign: existing wires to FT_IN (NO FT_ PREFIX - keep original names)
        verilog_code.push_str(&format!("assign {} = {{\n", ft_in_signal));
        for (i, signal_info) in output_to_input.iter().enumerate() {
            // IMPORTANT: Use original wire_name WITHOUT FT_ prefix in first assign
            if i < output_to_input.len() - 1 {
                verilog_code.push_str(&format!("    {},\n", signal_info.wire_name));
            } else {
                verilog_code.push_str(&format!("    {}\n", signal_info.wire_name));
            }
        }
        verilog_code.push_str("};\n\n");
        
        // Wire declarations for FT_OUT and individual FT_ wires
        if !ft_width.is_empty() {
            verilog_code.push_str(&format!("// wire {} {};\n", ft_width, ft_out_signal));
        } else {
            verilog_code.push_str(&format!("// wire {};\n", ft_out_signal));
        }
        
        for signal_info in output_to_input {
            let bit_count = self.calculate_bit_count(&signal_info.port_width);
            let width_str = if bit_count > 1 {
                format!("{} ", signal_info.port_width)
            } else {
                String::new()
            };
            
            let sanitized_wire = self.sanitize_wire_name(&signal_info.wire_name);
            let ft_wire_name = format!("FT_{}", sanitized_wire);
            verilog_code.push_str(&format!("wire {}{}; \n", width_str, ft_wire_name));
            
            // Build replacement map for instance port modification
            replacement_map.insert(
                signal_info.wire_name.clone(),
                ft_wire_name.clone(),
            );
        }
        verilog_code.push_str("\n");
        
        // Second assign: FT_OUT to individual FT_ wires (WITH FT_ PREFIX)
        verilog_code.push_str("assign {\n");
        for (i, signal_info) in output_to_input.iter().enumerate() {
            let sanitized_wire = self.sanitize_wire_name(&signal_info.wire_name);
            let ft_wire_name = format!("FT_{}", sanitized_wire);
            if i < output_to_input.len() - 1 {
                verilog_code.push_str(&format!("    {},\n", ft_wire_name));
            } else {
                verilog_code.push_str(&format!("    {}\n", ft_wire_name));
            }
        }
        verilog_code.push_str(&format!("}} = {};\n\n", ft_out_signal));
        
        (verilog_code, replacement_map)
    }
    
    /// Helper function to replace wire name in port connection line
    /// 
    /// Strategy: Use space-removed version for matching, but perform replacement on original line
    /// This preserves the original formatting/alignment while still handling arbitrary whitespace
    fn replace_wire_in_port_connection(&self, line: &str, wire_name: &str, ft_name: &str) -> String {
        // Step 1: Check if replacement is needed using space-removed version
        let line_no_spaces: String = line.chars().filter(|c| !c.is_whitespace() || *c == '\n').collect();
        let wire_no_spaces: String = wire_name.chars().filter(|c| !c.is_whitespace()).collect();
        
        // Pattern to match: (wire_name)
        let pattern = format!("({})", wire_no_spaces);
        
        if !line_no_spaces.contains(&pattern) {
            // Pattern not found in space-removed version, try regex fallback
            use regex::Regex;
            let pattern_str = format!(r"\(\s*{}\s*\)", regex::escape(wire_name));
            
            if let Ok(re) = Regex::new(&pattern_str) {
                if re.is_match(line) {
                    // Match found, perform replacement on ORIGINAL line
                    return re.replace_all(line, format!("({})", ft_name)).to_string();
                }
            }
            
            // No match found
            return line.to_string();
        }
        
        // Step 2: Pattern found! Now replace in ORIGINAL line using regex to preserve formatting
        // Build a regex that matches the wire_name with arbitrary whitespace around it
        use regex::Regex;
        let pattern_str = format!(r"\(\s*{}\s*\)", regex::escape(wire_name));
        
        if let Ok(re) = Regex::new(&pattern_str) {
            // Replace in original line, keeping everything else (including spacing before parentheses)
            return re.replace_all(line, format!("({})", ft_name)).to_string();
        }
        
        // Fallback: return original line unchanged
        line.to_string()
    }
    
    /// Apply feedthrough modification to source Verilog file
    /// Uses the -g generated code and modifies port connections
    fn apply_feedthrough_modification(
        &self,
        top_module: &Module,
        module_path: &[String],
        connections: &[Vec<String>],
        exclude: &[String],
        source_file: &str,
        output_file: &str,
        debug: bool,
    ) -> Result<()> {
        use std::fs;
        use std::io::Write;
        
        println!("\n// Applying feedthrough modification...");
        println!("// Source file: {}", source_file);
        println!("// Output file: {}", output_file);
        
        // Read source file with size check
        let file_metadata = fs::metadata(source_file)
            .map_err(|e| ParseError::FileNotFound(format!("Failed to get file metadata {}: {}", source_file, e)))?;
        let file_size = file_metadata.len();
        println!("// Source file size: {} bytes ({:.2} MB)", file_size, file_size as f64 / 1024.0 / 1024.0);
        
        // Warn if file is very large (>100MB)
        if file_size > 100 * 1024 * 1024 {
            println!("//   WARNING: File is larger than 100MB, processing may be slow");
        }
        
        let source_content = fs::read_to_string(source_file)
            .map_err(|e| ParseError::FileNotFound(format!("Failed to read source file {}: {}", source_file, e)))?;
        
        // Collect signal information for modification
        // For output->input: modify target (B) instance's input ports
        // For input->output: modify source (A) instance's input ports
        let mut output_to_input: Vec<SignalInfo> = Vec::new();
        let mut input_to_output: Vec<SignalInfo> = Vec::new();
        
        // Extract instance names
        let from_inst_parts: Vec<&str> = module_path[0].split('.').collect();
        let to_inst_parts: Vec<&str> = module_path[1].split('.').collect();
        let from_inst_name = from_inst_parts.last().copied().unwrap_or(module_path[0].as_str());
        let to_inst_name = to_inst_parts.last().copied().unwrap_or(module_path[1].as_str());
        
        // Find both instances to get port line numbers
        let source_instance = top_module.instances.iter()
            .find(|inst| inst.name == from_inst_name);
        let target_instance = top_module.instances.iter()
            .find(|inst| inst.name == to_inst_name);
        
        for conn_chain in connections {
            if conn_chain.len() < 2 {
                continue;
            }
            
            // Check exclusion
            let should_exclude = if !exclude.is_empty() {
                let first_signal = &conn_chain[0];
                exclude.iter().any(|pattern| first_signal.contains(pattern))
            } else {
                false
            };
            
            if should_exclude {
                continue;
            }
            
            let from_port = &conn_chain[0];
            let to_port = &conn_chain[1];
            
            // Get port information and directions
            let (from_direction, from_width) = self.get_port_info(top_module, &module_path[0], from_port);
            let (to_direction, to_width) = self.get_port_info(top_module, &module_path[1], to_port);
            
            // Categorize by direction:
            // - output->input: modify target (B) instance's input port
            // - input->output: modify source (A) instance's input port
            let process_connection = match (from_direction.as_str(), to_direction.as_str()) {
                ("output", "input") => Some((true, &to_direction, &to_width)),  // output->input, process target
                ("input", "output") => Some((false, &from_direction, &from_width)), // input->output, process source
                _ => None,  // Skip invalid combinations
            };
            
            if process_connection.is_none() {
                continue;
            }
            
            let (is_output_to_input, port_direction, port_width) = process_connection.unwrap();
            
            // Get the connecting wire name
            let wire_name = self.get_connecting_wire(top_module, &top_module.name, &module_path[1], to_port)
                .unwrap_or_else(|| format!("wire_{}_to_{}", from_port, to_port));
            
            // Calculate actual wire width
            let actual_wire_width = self.calculate_wire_actual_width(&wire_name, port_width);
            
            // Get line numbers based on direction
            let (port_to_modify, port_line, instance_for_modification) = if is_output_to_input {
                // output->input: modify target (B) instance's input port
                let line = if let Some(inst) = target_instance {
                    inst.port_connections.iter()
                        .find(|pc| pc.port_name == *to_port)
                        .map(|pc| {
                            if pc.line_number > 0 && inst.line_number_start > 0 {
                                inst.line_number_start + pc.line_number - 1
                            } else {
                                0
                            }
                        })
                        .unwrap_or(0)
                } else {
                    0
                };
                (to_port.clone(), line, target_instance)
            } else {
                // input->output: modify source (A) instance's input port
                let line = if let Some(inst) = source_instance {
                    inst.port_connections.iter()
                        .find(|pc| pc.port_name == *from_port)
                        .map(|pc| {
                            if pc.line_number > 0 && inst.line_number_start > 0 {
                                inst.line_number_start + pc.line_number - 1
                            } else {
                                0
                            }
                        })
                        .unwrap_or(0)
                } else {
                    0
                };
                (from_port.clone(), line, source_instance)
            };
            
            let signal_info = SignalInfo {
                from_port: from_port.clone(),
                to_port: to_port.clone(),
                wire_name: wire_name.clone(),
                from_direction: from_direction.clone(),
                to_direction: to_direction.clone(),
                port_width: actual_wire_width,
                from_port_line: if is_output_to_input { 0 } else { port_line },
                to_port_line: if is_output_to_input { port_line } else { 0 },
            };
            
            if is_output_to_input {
                output_to_input.push(signal_info);
            } else {
                input_to_output.push(signal_info);
            }
        }
        
        if output_to_input.is_empty() && input_to_output.is_empty() {
            println!("// No valid connections to modify.");
            return Ok(());
        }
        
        println!("// Found {} output->input connections to modify", output_to_input.len());
        println!("// Found {} input->output connections to modify", input_to_output.len());
        
        // Combine all signals for code generation
        let mut all_signals = output_to_input.clone();
        all_signals.extend(input_to_output.clone());
        
        // Extract instance names for FT signal naming
        let from_inst_parts: Vec<&str> = module_path[0].split('.').collect();
        let to_inst_parts: Vec<&str> = module_path[1].split('.').collect();
        let from_inst_name = from_inst_parts.last().copied().unwrap_or(module_path[0].as_str());
        let to_inst_name = to_inst_parts.last().copied().unwrap_or(module_path[1].as_str());
        
        // Generate feedthrough code using the new function
        let (verilog_code, replacement_map) = self.generate_feedthrough_code(
            &all_signals,
            from_inst_name,
            to_inst_name,
        );
        
        println!("// Generated code to insert:");
        for line in verilog_code.lines() {
            println!("//   {}", line);
        }
        
        // Now modify the source content
        let mut modified_content = source_content.clone();
        
        // Extract instance names
        let source_inst_name = from_inst_parts.last().copied().unwrap_or(module_path[0].as_str());
        let target_inst_name = to_inst_parts.last().copied().unwrap_or(module_path[1].as_str());
        
        println!("// Port connection replacements:");
        for (wire, ft_wire) in &replacement_map {
            println!("//   {} -> {}", wire, ft_wire);
        }
        
        // Split content into lines
        let lines: Vec<&str> = modified_content.lines().collect();
        
        // Use the new locate_instance_in_source function to find instance ranges
        let source_range = if let Some(src_inst) = source_instance {
            let hint = if src_inst.line_number_start > 0 && src_inst.line_number_end > 0 {
                Some((src_inst.line_number_start as usize, src_inst.line_number_end as usize))
            } else {
                None
            };
            self.locate_instance_in_source(&lines, source_inst_name, hint)
        } else {
            println!("// Warning: Source instance '{}' not found in parsed module", source_inst_name);
            None
        };
        
        let target_range = if let Some(tgt_inst) = target_instance {
            let hint = if tgt_inst.line_number_start > 0 && tgt_inst.line_number_end > 0 {
                Some((tgt_inst.line_number_start as usize, tgt_inst.line_number_end as usize))
            } else {
                None
            };
            self.locate_instance_in_source(&lines, target_inst_name, hint)
        } else {
            println!("// Warning: Target instance '{}' not found in parsed module", target_inst_name);
            None
        };
        
        // Process port replacements using locate_port_in_instance for better performance
        // For output->input: only modify target (B) instance
        // For input->output: only modify source (A) instance
        let mut replacement_count = 0;
        let mut lines_to_modify: HashMap<usize, Vec<(String, String)>> = HashMap::new();
        
        // Process output->input connections (modify target instance only)
        for signal_info in &output_to_input {
            let wire_name = &signal_info.wire_name;
            
            // Safely get FT name from replacement_map
            let ft_name = match replacement_map.get(wire_name) {
                Some(name) => name,
                None => {
                    println!("//   Error: Wire '{}' not found in replacement_map", wire_name);
                    continue;
                }
            };
            
            // Only locate and modify port in TARGET instance for output->input
            if let Some(target_range_val) = target_range {
                let mut found = false;
                if signal_info.to_port_line > 0 {
                    let line_idx = (signal_info.to_port_line as usize).saturating_sub(1);
                    if line_idx < lines.len() && line_idx >= target_range_val.0 && line_idx <= target_range_val.1 {
                        let line = lines[line_idx];
                        if line.contains(wire_name) {
                            lines_to_modify.entry(line_idx)
                                .or_insert_with(Vec::new)
                                .push((wire_name.clone(), ft_name.clone()));
                            found = true;
                            if debug {
                                println!("//   [Target:{}] Port '{}' at line {} (exact)",
                                        target_inst_name, signal_info.to_port, signal_info.to_port_line);
                            }
                        }
                    }
                }
                
                if !found {
                    if let Some(port_line) = self.locate_port_in_instance(&lines, target_range_val, &signal_info.to_port, target_inst_name, true) {
                        lines_to_modify.entry(port_line)
                            .or_insert_with(Vec::new)
                            .push((wire_name.clone(), ft_name.clone()));
                        if debug {
                            println!("//   [Target:{}] Port '{}' at line {} (located)",
                                    target_inst_name, signal_info.to_port, port_line + 1);
                        }
                    } else {
                        println!("//   Warning: Could not locate port '{}' in target instance '{}'",
                                signal_info.to_port, target_inst_name);
                    }
                }
            }
        }
        
        // Process input->output connections (modify source instance only)
        for signal_info in &input_to_output {
            let wire_name = &signal_info.wire_name;
            
            // Safely get FT name from replacement_map
            let ft_name = match replacement_map.get(wire_name) {
                Some(name) => name,
                None => {
                    println!("//   Error: Wire '{}' not found in replacement_map", wire_name);
                    continue;
                }
            };
            
            // Only locate and modify port in SOURCE instance for input->output
            if let Some(source_range_val) = source_range {
                let mut found = false;
                if signal_info.from_port_line > 0 {
                    let line_idx = (signal_info.from_port_line as usize).saturating_sub(1);
                    if line_idx < lines.len() && line_idx >= source_range_val.0 && line_idx <= source_range_val.1 {
                        let line = lines[line_idx];
                        if line.contains(wire_name) {
                            lines_to_modify.entry(line_idx)
                                .or_insert_with(Vec::new)
                                .push((wire_name.clone(), ft_name.clone()));
                            found = true;
                            if debug {
                                println!("//   [Source:{}] Port '{}' at line {} (exact)",
                                        source_inst_name, signal_info.from_port, signal_info.from_port_line);
                            }
                        }
                    }
                }
                
                if !found {
                    if let Some(port_line) = self.locate_port_in_instance(&lines, source_range_val, &signal_info.from_port, source_inst_name, true) {
                        lines_to_modify.entry(port_line)
                            .or_insert_with(Vec::new)
                            .push((wire_name.clone(), ft_name.clone()));
                        if debug {
                            println!("//   [Source:{}] Port '{}' at line {} (located)",
                                    source_inst_name, signal_info.from_port, port_line + 1);
                        }
                    } else {
                        println!("//   Warning: Could not locate port '{}' in source instance '{}'",
                                signal_info.from_port, source_inst_name);
                    }
                }
            }
        }
        
        // Apply all replacements
        let mut modified_lines: Vec<String> = Vec::new();
        if debug {
            println!("\n// === Starting wire replacement process ===");
            println!("// Total lines in file: {}", lines.len());
            println!("// Total lines to modify: {}", lines_to_modify.len());
        }
        
        // Validate all line indices before processing
        let mut invalid_indices = Vec::new();
        for line_idx in lines_to_modify.keys() {
            if *line_idx >= lines.len() {
                invalid_indices.push(*line_idx);
            }
        }
        
        if !invalid_indices.is_empty() {
            println!("//   ERROR: Found {} invalid line indices (out of bounds):", invalid_indices.len());
            for idx in &invalid_indices {
                println!("//     Line {} exceeds file length {}", idx + 1, lines.len());
            }
            return Err(ParseError::FileNotFound(format!("Line index out of bounds")));
        }
        
        if debug {
            for (line_idx, replacements) in &lines_to_modify {
                println!("//   Line {}: {} replacement(s) needed", line_idx + 1, replacements.len());
                for (wire, ft) in replacements {
                    println!("//     '{}' -> '{}'", wire, ft);
                }
            }
            println!("// ===");
        }
        
        for (line_num, line) in lines.iter().enumerate() {
            let mut modified_line = line.to_string();
            
            if let Some(replacements) = lines_to_modify.get(&line_num) {
                if debug {
                    println!("\n// Processing line {} (0-based: {})", line_num + 1, line_num);
                    println!("//   Original: {}", line.trim());
                }
                
                for (wire_name, ft_name) in replacements {
                    if debug {
                        println!("//   Attempting replacement: '{}' -> '{}'", wire_name, ft_name);
                        
                        // Check if wire_name exists in the line
                        if !line.contains(wire_name) {
                            println!("//   ⚠️  Wire name '{}' NOT FOUND in line!", wire_name);
                            println!("//   Line content: '{}'", line);
                        } else {
                            println!("//   ✓ Wire name '{}' found in line", wire_name);
                        }
                    }
                    
                    let old_line = modified_line.clone();
                    modified_line = self.replace_wire_in_port_connection(&modified_line, wire_name, ft_name);
                    
                    if old_line != modified_line {
                        if debug {
                            println!("//   ✓ Replacement successful!");
                            println!("//   Modified: {}", modified_line.trim());
                        }
                        replacement_count += 1;
                    } else if debug {
                        println!("//   ✗ Replacement FAILED - line unchanged");
                        println!("//   Checking patterns:");
                        println!("//     '({})' found: {}", wire_name, old_line.contains(&format!("({})", wire_name)));
                        println!("//     '({} )' found: {}", wire_name, old_line.contains(&format!("({} )", wire_name)));
                        println!("//     '( {})' found: {}", wire_name, old_line.contains(&format!("( {})", wire_name)));
                        println!("//     '( {} )' found: {}", wire_name, old_line.contains(&format!("( {} )", wire_name)));
                    }
                }
            }
            
            modified_lines.push(modified_line);
        }
        
        modified_content = modified_lines.join("\n");
        
        // Step 2: Insert wire declarations and assigns before the first instance
        // Find which instance (source or target) appears first in the file
        let first_inst_for_insertion = if let (Some((src_start, _)), Some((tgt_start, _))) = (source_range, target_range) {
            // Compare the start positions and use the earlier one
            if src_start < tgt_start {
                source_instance.map(|inst| (inst, src_start))
            } else {
                target_instance.map(|inst| (inst, tgt_start))
            }
        } else if source_range.is_some() {
            source_instance.and_then(|inst| source_range.map(|(start, _)| (inst, start)))
        } else if target_range.is_some() {
            target_instance.and_then(|inst| target_range.map(|(start, _)| (inst, start)))
        } else {
            None
        };
        
        if let Some((first_inst, first_inst_line)) = first_inst_for_insertion {
            println!("// Inserting code before first instance '{}' at line {}", first_inst.name, first_inst_line + 1);
            
            let mut lines: Vec<String> = modified_content.lines().map(|s| s.to_string()).collect();
            
            if first_inst_line < lines.len() {
                // Find indentation from the instance line
                let instance_line = &lines[first_inst_line];
                let indent = instance_line.chars().take_while(|c| c.is_whitespace()).collect::<String>();
                
                // Add indentation to generated code
                let code_lines: Vec<String> = verilog_code.lines()
                    .map(|line| {
                        if line.trim().is_empty() {
                            String::new()
                        } else {
                            format!("{}{}", indent, line)
                        }
                    })
                    .collect();
                
                // Insert all lines at once
                for (i, code_line) in code_lines.iter().enumerate() {
                    lines.insert(first_inst_line + i, code_line.to_string());
                }
                
                modified_content = lines.join("\n");
                println!("// Code insertion completed");
            } else {
                println!("// Warning: Instance line {} out of range", first_inst_line);
            }
        } else {
            println!("// Warning: Could not locate either source or target instance for code insertion");
        }
        
        // Write to output file
        let mut output = fs::File::create(output_file)
            .map_err(|e| ParseError::FileNotFound(format!("Failed to create output file {}: {}", output_file, e)))?;
        output.write_all(modified_content.as_bytes())
            .map_err(|e| ParseError::FileNotFound(format!("Failed to write output file: {}", e)))?;
        
        println!("// Feedthrough modification completed.");
        println!("// Modified {} connections (actual replacements: {})", output_to_input.len() + input_to_output.len(), replacement_count);
        println!("// Output written to: {}", output_file);
        
        Ok(())
    }
    
    /// 查找信号连接链
    fn find_signal_connections(
        &self,
        top_module: &Module,
        module_path: &[String],
    ) -> Result<Vec<Vec<String>>> {
        let mut result = Vec::new();
        
        if module_path.is_empty() {
            return Ok(result);
        }
        
        // 如果只有一个模块，显示该模块的所有端口
        if module_path.len() == 1 {
            let mod_name = &module_path[0];
            
            // 检查是否是顶层模块
            if mod_name == &top_module.name {
                for port in &top_module.ports {
                    result.push(vec![format!("{} ({})", port.name, port.direction)]);
                }
            } else {
                // 子模块
                let inst = top_module.instances.iter()
                    .find(|i| i.name == *mod_name)
                    .ok_or_else(|| ParseError::ModuleNotFound(format!("Submodule {} not found", mod_name)))?;
                
                if let Some(mod_def) = self.database.modules.iter().find(|m| m.name == inst.module_name) {
                    for port in &mod_def.ports {
                        result.push(vec![format!("{} ({})", port.name, port.direction)]);
                    }
                }
            }
            
            return Ok(result);
        }
        
        // NOTE: module_path is already expanded by trace_signals, so don't expand again
        // 两个或多个模块：追踪连接
        for i in 0..module_path.len() - 1 {
            let from_mod = &module_path[i];
            let to_mod = &module_path[i + 1];
            
            // 获取这两个模块之间的连接
            let conns = self.find_connections_between(
                top_module,
                from_mod,
                to_mod,
            )?;
            
            // 合并到结果
            if i == 0 {
                result = conns;
            } else {
                // 将新的连接追加到已有链
                result = self.merge_connections(result, conns);
            }
        }
        
        Ok(result)
    }
    
    /// Expand hierarchical paths to include intermediate steps
    /// 
    /// Example:
    /// Input:  ["m3_core_grp_dn_u", "tcn_wrapper_u.cpuss_u0"]
    /// Output: ["m3_core_grp_dn_u", "tcn_wrapper_u", "tcn_wrapper_u.cpuss_u0"]
    /// 
    /// Input:  ["tcn_wrapper_u.cpuss_u0", "m3_core_grp_dn_u"]
    /// Output: ["tcn_wrapper_u.cpuss_u0", "tcn_wrapper_u", "m3_core_grp_dn_u"]
    fn expand_hierarchical_path(&self, module_path: &[String]) -> Result<Vec<String>> {
        let mut expanded = Vec::new();
        
        for (idx, path) in module_path.iter().enumerate() {
            // Check if this is a hierarchical path (contains dots)
            if path.contains('.') {
                let parts: Vec<&str> = path.split('.').collect();
                
                // Determine if we need to add intermediate steps before or after
                // based on position in the path
                if idx == 0 {
                    // First element: add current, then build upward to parent
                    // For "tcn_wrapper_u.cpuss_u0", add:
                    //   1. "tcn_wrapper_u.cpuss_u0" (current)
                    //   2. "tcn_wrapper_u" (parent)
                    expanded.push(path.clone());
                    
                    // Add intermediate levels in reverse order (child to parent)
                    for i in (0..parts.len() - 1).rev() {
                        let intermediate = parts[0..=i].join(".");
                        expanded.push(intermediate);
                    }
                } else if idx == module_path.len() - 1 {
                    // Last element: build downward from parent to current
                    // For "tcn_wrapper_u.cpuss_u0", add:
                    //   1. "tcn_wrapper_u" (parent)
                    //   2. "tcn_wrapper_u.cpuss_u0" (current)
                    
                    // Add intermediate levels in forward order (parent to child)
                    for i in 0..parts.len() - 1 {
                        let intermediate = parts[0..=i].join(".");
                        if expanded.is_empty() || expanded.last().unwrap() != &intermediate {
                            expanded.push(intermediate);
                        }
                    }
                    expanded.push(path.clone());
                } else {
                    // Middle element: add all intermediate steps
                    for i in 0..parts.len() {
                        let intermediate = parts[0..=i].join(".");
                        if expanded.is_empty() || expanded.last().unwrap() != &intermediate {
                            expanded.push(intermediate);
                        }
                    }
                }
            } else {
                // Simple path, just add it
                expanded.push(path.clone());
            }
        }
        
        Ok(expanded)
    }
    
    /// Resolve hierarchical instance path and return the actual context module and instance name
    /// For example: "m3_core_grp_dn_u.top_crg_wrapper_u" returns the module definition of m3_core_grp_dn_u
    /// and the instance name "top_crg_wrapper_u"
    fn resolve_hierarchical_path<'a>(
        &'a self,
        top_module: &'a Module,
        path: &'a str,
    ) -> Result<(&'a Module, &'a str)> {
        // Check if path contains hierarchy (dots)
        if !path.contains('.') {
            // Simple path - instance is directly in top module
            return Ok((top_module, path));
        }
        
        // Split hierarchical path: "inst1.inst2.inst3" -> ["inst1", "inst2", "inst3"]
        let parts: Vec<&str> = path.split('.').collect();
        
        if parts.is_empty() {
            return Err(ParseError::ModuleNotFound(format!("Invalid path: {}", path)));
        }
        
        // Navigate through the hierarchy to find the parent module
        let mut current_module = top_module;
        
        // Navigate to the parent of the last instance
        for i in 0..parts.len() - 1 {
            let inst_name = parts[i];
            
            // Find instance in current module
            let inst = current_module.instances.iter()
                .find(|inst| inst.name == inst_name)
                .ok_or_else(|| ParseError::ModuleNotFound(
                    format!("Instance {} not found in path {}", inst_name, path)
                ))?;
            
            // Get the module definition for this instance
            current_module = self.database.modules.iter()
                .find(|m| m.name == inst.module_name)
                .ok_or_else(|| ParseError::ModuleNotFound(
                    format!("Module definition {} not found for instance {}", inst.module_name, inst_name)
                ))?;
        }
        
        // Return the parent module and the final instance name
        let final_inst_name = parts[parts.len() - 1];
        Ok((current_module, final_inst_name))
    }
    
    /// Find connections between two modules
    fn find_connections_between(
        &self,
        top_module: &Module,
        from_module: &str,
        to_module: &str,
    ) -> Result<Vec<Vec<String>>> {
        let mut connections = Vec::new();
        
        // Check if to_module is a child of from_module (hierarchical relationship)
        // For example: from="tcn_wrapper_u", to="tcn_wrapper_u.cpuss_u0"
        if to_module.starts_with(&format!("{}.", from_module)) {
            // This is a parent->child relationship
            // We need to find connections inside the parent module
            
            // Resolve the parent module
            let (parent_context, parent_inst_name) = self.resolve_hierarchical_path(top_module, from_module)?;
            let parent_inst = parent_context.instances.iter()
                .find(|i| i.name == parent_inst_name)
                .ok_or_else(|| ParseError::ModuleNotFound(format!("Parent instance {} not found", from_module)))?;
            
            // Get the parent module definition
            let parent_mod_def = self.database.modules.iter()
                .find(|m| m.name == parent_inst.module_name)
                .ok_or_else(|| ParseError::ModuleNotFound(format!("Module definition {} not found", parent_inst.module_name)))?;
            
            // Resolve the child module path
            let (child_context, child_inst_name) = self.resolve_hierarchical_path(top_module, to_module)?;
            let child_inst = child_context.instances.iter()
                .find(|i| i.name == child_inst_name)
                .ok_or_else(|| ParseError::ModuleNotFound(format!("Child instance {} not found", to_module)))?;
            
            // Get the child module definition
            let child_mod_def = self.database.modules.iter()
                .find(|m| m.name == child_inst.module_name);
            
            // If child module is not defined, we can't reliably trace connections into it
            // Skip this hierarchical relationship and return empty
            if child_mod_def.is_none() {
                eprintln!("Warning: Module definition '{}' for instance '{}' not found. Cannot trace hierarchical connections.",
                    child_inst.module_name, to_module);
                return Ok(connections);
            }
            
            let child_mod_def = child_mod_def.unwrap();
            
            // Build mapping: parent module port -> child instance port
            // Iterate through child's port connections and find which parent ports they connect to
            for child_port_conn in &child_inst.port_connections {
                let signals = self.extract_signal_names(&child_port_conn.signal_expr);
                
                // For each signal connected to this child port
                for signal in signals {
                    // Check if this signal is a port in the parent module
                    if let Some(parent_port) = parent_mod_def.ports.iter().find(|p| p.name == signal) {
                        connections.push(vec![
                            parent_port.name.clone(),
                            child_port_conn.port_name.clone()
                        ]);
                    }
                }
            }
            
            return Ok(connections);
        }
        
        // Check if from_module is a child of to_module (reverse hierarchical relationship)
        if from_module.starts_with(&format!("{}.", to_module)) {
            // This is a child->parent relationship  
            // Similar logic but reversed
            
            let (child_context, child_inst_name) = self.resolve_hierarchical_path(top_module, from_module)?;
            let child_inst = child_context.instances.iter()
                .find(|i| i.name == child_inst_name)
                .ok_or_else(|| ParseError::ModuleNotFound(format!("Child instance {} not found", from_module)))?;
            
            let (parent_context, parent_inst_name) = self.resolve_hierarchical_path(top_module, to_module)?;
            let parent_inst = parent_context.instances.iter()
                .find(|i| i.name == parent_inst_name)
                .ok_or_else(|| ParseError::ModuleNotFound(format!("Parent instance {} not found", to_module)))?;
            
            let parent_mod_def = self.database.modules.iter()
                .find(|m| m.name == parent_inst.module_name)
                .ok_or_else(|| ParseError::ModuleNotFound(format!("Module definition {} not found", parent_inst.module_name)))?;
            
            // For each child port connection
            for child_port_conn in &child_inst.port_connections {
                let signals = self.extract_signal_names(&child_port_conn.signal_expr);
                
                // Check if connected to parent module port
                for signal in signals {
                    if parent_mod_def.ports.iter().any(|p| p.name == signal) {
                        connections.push(vec![
                            child_port_conn.port_name.clone(),
                            signal.clone()
                        ]);
                    }
                }
            }
            
            return Ok(connections);
        }
        
        // Handle top-level port connections
        let from_is_top = from_module == top_module.name;
        let to_is_top = to_module == top_module.name;
        
        if from_is_top && !to_is_top {
            // From top to submodule: resolve hierarchical path for to_module
            let (parent_module, to_inst_name) = self.resolve_hierarchical_path(top_module, to_module)?;
            
            let to_inst = parent_module.instances.iter()
                .find(|i| i.name == to_inst_name)
                .ok_or_else(|| ParseError::ModuleNotFound(format!("Submodule {} not found", to_module)))?;
            
            // Traverse submodule port connections
            for port_conn in &to_inst.port_connections {
                let signal_names = self.extract_signal_names(&port_conn.signal_expr);
                
                // Check if any signal is a top-level port
                for signal_name in signal_names {
                    if top_module.ports.iter().any(|p| p.name == signal_name) {
                        connections.push(vec![
                            signal_name.clone(),
                            port_conn.port_name.clone()
                        ]);
                    }
                }
            }
        } else if !from_is_top && to_is_top {
            // From submodule to top: resolve hierarchical path for from_module
            let (parent_module, from_inst_name) = self.resolve_hierarchical_path(top_module, from_module)?;
            
            let from_inst = parent_module.instances.iter()
                .find(|i| i.name == from_inst_name)
                .ok_or_else(|| ParseError::ModuleNotFound(format!("Submodule {} not found", from_module)))?;
            
            for port_conn in &from_inst.port_connections {
                let signal_names = self.extract_signal_names(&port_conn.signal_expr);
                
                // Check if any signal is a top-level port
                for signal_name in signal_names {
                    if top_module.ports.iter().any(|p| p.name == signal_name) {
                        connections.push(vec![
                            port_conn.port_name.clone(),
                            signal_name.clone()
                        ]);
                    }
                }
            }
        } else if !from_is_top && !to_is_top {
            // Between two submodules: resolve hierarchical paths for both
            let (from_parent_module, from_inst_name) = self.resolve_hierarchical_path(top_module, from_module)?;
            let (to_parent_module, to_inst_name) = self.resolve_hierarchical_path(top_module, to_module)?;
            
            let from_inst = from_parent_module.instances.iter()
                .find(|i| i.name == from_inst_name)
                .ok_or_else(|| ParseError::ModuleNotFound(format!("Submodule {} not found", from_module)))?;
            
            let to_inst = to_parent_module.instances.iter()
                .find(|i| i.name == to_inst_name)
                .ok_or_else(|| ParseError::ModuleNotFound(format!("Submodule {} not found", to_module)))?;
            
            // Build signal name to port mapping
            let mut from_signals: HashMap<String, Vec<String>> = HashMap::new();
            let mut to_signals: HashMap<String, Vec<String>> = HashMap::new();
            
            for port_conn in &from_inst.port_connections {
                let signals = self.extract_signal_names(&port_conn.signal_expr);
                for signal in signals {
                    if !signal.is_empty() {
                        from_signals.entry(signal)
                            .or_insert_with(Vec::new)
                            .push(port_conn.port_name.clone());
                    }
                }
            }
            
            for port_conn in &to_inst.port_connections {
                let signals = self.extract_signal_names(&port_conn.signal_expr);
                for signal in signals {
                    if !signal.is_empty() {
                        to_signals.entry(signal)
                            .or_insert_with(Vec::new)
                            .push(port_conn.port_name.clone());
                    }
                }
            }
            
            // Find common signals
            for (signal, from_ports) in &from_signals {
                if let Some(to_ports) = to_signals.get(signal) {
                    // Only add one connection per signal, not a Cartesian product
                    // Use the first port from each side to represent the connection
                    if !from_ports.is_empty() && !to_ports.is_empty() {
                        connections.push(vec![
                            from_ports[0].clone(),
                            to_ports[0].clone()
                        ]);
                    }
                }
            }
        }
        
        Ok(connections)
    }
    
    /// 合并连接链
    fn merge_connections(
        &self,
        existing: Vec<Vec<String>>,
        new_conns: Vec<Vec<String>>,
    ) -> Vec<Vec<String>> {
        let mut result = Vec::new();
        
        for exist_chain in &existing {
            let last_signal = exist_chain.last().unwrap();
            
            // 查找匹配的新连接
            let mut found = false;
            for new_conn in &new_conns {
                if new_conn.len() >= 2 && &new_conn[0] == last_signal {
                    let mut new_chain = exist_chain.clone();
                    new_chain.push(new_conn[1].clone());
                    result.push(new_chain);
                    found = true;
                }
            }
            
            // 如果没找到匹配，保留原链但添加空占位
            if !found {
                let mut new_chain = exist_chain.clone();
                new_chain.push("---".to_string());
                result.push(new_chain);
            }
        }
        
        result
    }
    
    /// 显示特定信号的所有连接关系
    /// 根据信号名查找所有连接到该信号的实例端口
    pub fn show_signal_connections(&self, top_module_name: &str, signal_name: &str) -> Result<()> {
        // 获取顶层模块
        let top_module = self.database.modules.iter()
            .find(|m| m.name == top_module_name)
            .ok_or_else(|| ParseError::ModuleNotFound(top_module_name.to_string()))?;
        
        println!("\nModule: {}", top_module_name);
        println!("Signal Connections for: {}", signal_name);
        println!("{}", "=".repeat(100));
        
        // 表头 - 增加 Connection 列
        println!("{:<30} | {:<30} | {:<15} | {:<20}", "Instance", "Port", "Direction", "Connection");
        println!("{}", "-".repeat(100));
        
        let mut connection_count = 0;
        
        // 检查顶层端口连接
        for port in &top_module.ports {
            if port.name == signal_name {
                println!("{:<30} | {:<30} | {:<15} | {:<20}", "<TOP>", port.name, port.direction, signal_name);
                connection_count += 1;
            }
        }
        
        // 检查所有实例的端口连接
        for instance in &top_module.instances {
            // 查找实例对应的模块定义
            if let Some(instance_module) = self.database.modules.iter().find(|m| m.name == instance.module_name) {
                // 检查实例的每个端口连接
                for port_conn in &instance.port_connections {
                    // Extract signal names from the connection expression
                    let connected_signals = self.extract_signal_names(&port_conn.signal_expr);
                    
                    // Check if either the signal appears in the connection OR the port name matches
                    // (avoid printing duplicate when both are true)
                    if connected_signals.contains(&signal_name.to_string()) || port_conn.port_name == signal_name {
                        // Get port direction
                        let direction = instance_module.ports.iter()
                            .find(|p| p.name == port_conn.port_name)
                            .map(|p| p.direction.as_str())
                            .unwrap_or("unknown");
                        
                        // Display the connection
                        println!("{:<30} | {:<30} | {:<15} | {:<20}", 
                            instance.name, 
                            port_conn.port_name, 
                            direction,
                            port_conn.signal_expr);
                        connection_count += 1;
                    }
                }
            }
        }
        
        println!("{}", "=".repeat(100));
        println!("Total connections found: {}", connection_count);
        println!();
        
        if connection_count == 0 {
            println!("No connections found for signal: {}", signal_name);
        }
        
        Ok(())
    }
    /// Get direction abbreviation (i, o, io)
    fn get_direction_abbreviation(&self, direction: &str) -> &str {
        match direction {
            "input" => "i",
            "output" => "o",
            "inout" => "io",
            _ => "",
        }
    }
    
    /// Get the connecting wire name between modules
    fn get_connecting_wire(&self, top_module: &Module, parent_path: &str, inst_path: &str, port_name: &str) -> Option<String> {
        // Parse the instance path to get the actual instance name
        let parts: Vec<&str> = inst_path.split('.').collect();
        let inst_name = parts.last().copied().unwrap_or(inst_path);
        
        // Find the instance in the parent module (which could be top or a nested module)
        let instance = if parent_path == top_module.name {
            // Parent is top module
            top_module.instances.iter().find(|i| i.name == inst_name)
        } else {
            // Parent is a submodule - need to find it first
            let parent_parts: Vec<&str> = parent_path.split('.').collect();
            let parent_inst_name = parent_parts.last().copied().unwrap_or(parent_path);
            if let Some(parent_inst) = top_module.instances.iter().find(|i| i.name == parent_inst_name) {
                // Get the parent module definition
                if let Some(parent_mod) = self.database.modules.iter().find(|m| m.name == parent_inst.module_name) {
                    parent_mod.instances.iter().find(|i| i.name == inst_name)
                } else {
                    None
                }
            } else {
                None
            }
        };
        
        // Find the port connection for this port
        if let Some(inst) = instance {
            for port_conn in &inst.port_connections {
                if port_conn.port_name == port_name {
                    return Some(port_conn.signal_expr.clone());
                }
            }
        }
        
        None
    }
    
    /// Calculate bit count from width string
    fn calculate_bit_count(&self, width_str: &str) -> u32 {
        if width_str.is_empty() {
            return 1; // Default single bit
        }
        
        // Remove brackets if present
        let clean_width = width_str.trim().trim_start_matches('[').trim_end_matches(']');
        
        // Handle single bit notation like [0] or just 0
        if !clean_width.contains(':') {
            // Could be a single number like "0" or a parameter
            if clean_width.chars().all(|c| c.is_ascii_digit()) {
                let msb: std::result::Result<u32, std::num::ParseIntError> = clean_width.parse();
                return msb.unwrap_or(0) + 1;
            } else {
                // Parameter or unknown width
                return 0; // Unknown width
            }
        }
        
        // Handle range notation like [7:0]
        let parts: Vec<&str> = clean_width.split(':').collect();
        if parts.len() == 2 {
            let msb: std::result::Result<u32, std::num::ParseIntError> = parts[0].trim().parse();
            let lsb: std::result::Result<u32, std::num::ParseIntError> = parts[1].trim().parse();
            
            if let (Ok(msb_val), Ok(lsb_val)) = (msb, lsb) {
                return msb_val - lsb_val + 1;
            }
        }
        
        0 // Unknown width
    }
    
    /// Get signal bit count for a specific module and signal
    fn get_signal_bit_count(&self, top_module: &Module, module_name: &str, signal_name: &str) -> u32 {
        // Check if this is the top module
        if module_name == top_module.name {
            // Look up the signal in top module ports
            if let Some(port) = top_module.ports.iter().find(|p| p.name == signal_name) {
                return self.calculate_bit_count(&port.width);
            }
        } else {
            // Look for the instance in the top module
            if let Some(inst) = top_module.instances.iter().find(|i| i.name == module_name) {
                // Get the module definition
                if let Some(mod_def) = self.database.modules.iter().find(|m| m.name == inst.module_name) {
                    // Look up the signal in the module ports
                    if let Some(port) = mod_def.ports.iter().find(|p| p.name == signal_name) {
                        return self.calculate_bit_count(&port.width);
                    }
                }
            }
        }
        
        // Unknown width
        0
    }
    
    /// Get port information (direction and width) for a specific module and signal
    /// Returns (direction, width) tuple
    /// Supports hierarchical paths like "inst1.inst2"
    fn get_port_info(&self, top_module: &Module, module_name: &str, signal_name: &str) -> (String, String) {
        // Check if this is the top module
        if module_name == top_module.name {
            // Look up the signal in top module ports
            if let Some(port) = top_module.ports.iter().find(|p| p.name == signal_name) {
                return (port.direction.clone(), port.width.clone());
            }
        } else {
            // Try to resolve hierarchical path first
            if let Ok((parent_module, inst_name)) = self.resolve_hierarchical_path(top_module, module_name) {
                // Find the instance in the parent module
                if let Some(inst) = parent_module.instances.iter().find(|i| i.name == inst_name) {
                    // Try to find the module definition
                    let mut mod_def = self.database.modules.iter().find(|m| m.name == inst.module_name);
                    
                    // If not found and module_name ends with _stub, try without the suffix
                    if mod_def.is_none() && inst.module_name.ends_with("_stub") {
                        let base_name = &inst.module_name[..inst.module_name.len() - 5]; // Remove "_stub"
                        mod_def = self.database.modules.iter().find(|m| m.name == base_name);
                    }
                    
                    // If found, look up the port
                    if let Some(module_def) = mod_def {
                        if let Some(port) = module_def.ports.iter().find(|p| p.name == signal_name) {
                            return (port.direction.clone(), port.width.clone());
                        }
                    }
                }
            } else {
                // Fallback: try direct lookup in top_module for backward compatibility
                if let Some(inst) = top_module.instances.iter().find(|i| i.name == module_name) {
                    // Try to find the module definition
                    let mut mod_def = self.database.modules.iter().find(|m| m.name == inst.module_name);
                    
                    // If not found and module_name ends with _stub, try without the suffix
                    if mod_def.is_none() && inst.module_name.ends_with("_stub") {
                        let base_name = &inst.module_name[..inst.module_name.len() - 5]; // Remove "_stub"
                        mod_def = self.database.modules.iter().find(|m| m.name == base_name);
                    }
                    
                    // If found, look up the port
                    if let Some(module_def) = mod_def {
                        if let Some(port) = module_def.ports.iter().find(|p| p.name == signal_name) {
                            return (port.direction.clone(), port.width.clone());
                        }
                    } else {
                        // Module definition not found - try to find signal in top module ports as fallback
                        // This helps when tracing signals that connect to top-level ports
                        if let Some(port) = top_module.ports.iter().find(|p| p.name == signal_name) {
                            return (port.direction.clone(), port.width.clone());
                        }
                    }
                }
            }
        }
        
        // Unknown port
        (String::new(), String::new())
    }

}

impl Default for VerilogParser {
    fn default() -> Self {
        Self::new()
    }
}
